vuexjs getter with argument

≡放荡痞女 提交于 2019-12-01 02:13:05

One way to do this can be:

new Vuex.Store({
  getters: {
    someMethod(state){
      var self = this;
       return function (args) {
          // return data from store with query on args and self as this
       };       
    }
  }
})

However, getter does not take arguments and why is explained in this thread:

the naming convention is slightly confusing, getters indicates state can be retrieved in any form, but in fact they are reducers.

Perhaps we should have reducers being pure methods. Which can be used for filtering, mapping ect.

getters then can be given any context. Similar to computed, but you can now combine computed props to getters in vuex option. Which helps structure of components.

Edit:

A better way to achieve the same thing will be using ES6 arrow as detailed out in the answer of nivram80, using method style getters where you can pass a parameter by returning a function form the getter:

new Vuex.Store({
  getters: {
    someMethod: (state) => (id) => {
        return state.things.find(thing => thing.id === id)
      }
    };       
  }
})

An ES6 arrow function would work nice here too. For example sake, let's say you're looking for a particular 'thing' in your store.

new Vuex.Store({
  getters: {
    someMethod: (state) => (id) => {
        return state.things.find(thing => thing.id === id)
      }
    };       
  }
})

Here is another example via the Vuex documentation

You can use the MapGetters helper like this, once define store getters:

new Vuex.Store({
  getters: {
    someMethod(state){
       return (value) => {
          return value;
       }
    }
  }
})

Then call getter from a component like this:

<script>
    import { mapGetters } from "vuex"

    export default {
     computed: {
     ...mapGetters(['someMethod'])
     },
     mounted() {
       console.log(this.someMethod('hello world')); // then logs "hello world"
     }       
}
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!