Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple parameters to vuex getters?

In a vue.js component (using vuex), I have:

computed: {...
    filtered () {
      return this.withFilters(obj1, obj2) 

with withFilters a getter to define in the store. But how in the store can I get the arguments passed to withFilters and define this getter accordingly? For a 1-argument function I would have simply done something like

withFilter: state => obj1 => { ...

For example:

withFilter: state => obj1 => {
 for (var k in obj1) {
  obj1[k] !== null ? console.log('Not null!') : console.log('Null!')
 }
}

Not sure how to do it with a 2-argument function.

like image 668
MrNycticorax Avatar asked Sep 06 '18 00:09

MrNycticorax


People also ask

How to pass arguments to getters in Vue?

Note that getters accessed as properties are cached as part of Vue's reactivity system. You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store: Note that getters accessed via methods will run each time you call them, and the result is not cached.

What is a getter in a Vuex store?

Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed. The getters will be exposed on the store.getters object, and you access values as properties:

How to get all options from multiple getters into one object?

Suggested solution is to create a single getter, that accepts index as an argument and returns full list of options from getters.widgetsConfig. Note that if needed other getters may be re-used in order to collect necessary information into a single object.

Can I use Quasar code in a VUE project?

Even if the code below is paste from a Quasar project, it could be applied in any Vue project. In this Quasar project, I use Vuex in module mode. // src/store/myModule/getters.js export const myFunctionWithArgument = (state) => (myArgument) => { // it's an example return state.all [myArgument] }


1 Answers

You just need to define the function returned by your getter with multiple arguments. For example

getters: {
  withFilter (state) {
    return (obj1, obj2) => {
      // your code here
    }
  }
}

You could write this entirely with arrow functions but I think it looks messy (personal opinion)

withFilter: (state) => (obj1, obj2) => {
  // your code here
}

See the documentation on ES6 arrow functions and argument parentheses here...

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }

like image 187
Phil Avatar answered Sep 27 '22 23:09

Phil