Konrad Viltersten Konrad Viltersten - 8 days ago 6
Javascript Question

How to pass an argument to functions mapped using ...mapActions(...)?

Considering the following passage

export default {
methods: {
...mapActions(["updateData", "resetData"]);
}
}


I'd like to pass in a parameter into the called functions. Not certain how to do so properly while still retaining the
...mapAction()
call, I had to rewrite to the following.

export default {
methods: {
// ...mapActions(["updateData", "resetData"])
updateData: function() { this.$store.dispatch("updateData", "names") },
resetData: function() { this.$store.dispatch("resetData"); }
}
}


Is this the only way?

Answer

You can just pass the parameter to the method, where you are calling it. you can only send one parameter, which will be available in the actions. You don't have to do anything special when using mapActions

For example you can call it like:

<button @click=updateData({data1: 1, data2: 2})>

and in the vuex store:

const actions = {
  updateData: (state, data) => {
     //You will get passed parameter as data here
  },

and you can still use mapActions:

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}

see working fiddle here: you can see passed parameter in the alert :)


Here is the implementation of mapActions from vuex repo

export function mapActions (actions) {
  const res = {}
  normalizeMap(actions).forEach(({ key, val }) => {
    res[key] = function mappedAction (...args) {
      return this.$store.dispatch.apply(this.$store, [val].concat(args))
    }
  })
  return res
}

You can see it takes the args passed and puts them as a second argument of dispatch function.