How to pass 2 arguments to a getter in vuex?

by hal.littel , in category: Javascript , a year ago

How to pass 2 arguments to a getter in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , a year ago

@hal.littel 

In Vuex, you can't directly pass multiple arguments to a getter. However, you can achieve this by passing an object containing the arguments as a single argument to the getter. Here's how you can do it:

  1. Define your getter in your Vuex store:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// store.js
const store = new Vuex.Store({
  state: { // your state properties },
  getters: {
    getSomeData: (state) => (args) => {
      // getter logic that uses the arguments
      
      // access the arguments using args.argument1 and args.argument2
      // perform your logic and return the data
    }
  },
  // your mutations, actions, etc.
})


  1. Use the getter and pass the arguments in your component:
1
2
3
4
5
6
7
8
9
// MyComponent.vue
<script>
  computed: {
    someData() {
      // this.$store.getters.getSomeData({ argument1: value1, argument2: value2 })
      return this.$store.getters.getSomeData({ argument1: 'value1', argument2: 'value2' })
    }
  }
</script>


Now the getter getSomeData will receive the arguments as an object. You can then access the arguments inside the getter logic using args.argument1 and args.argument2.