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

Given the following passage

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

I would like to pass a parameter to the called functions. You do not know how to do this, while maintaining the call ...mapAction() , I had to rewrite the following code.

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

Is this the only way?

+6
source share
1 answer

You can simply pass the parameter to the method in which you call it. you can send only one parameter that will be available in actions. You do not need to do anything when using mapActions

For example, you can call it like this:

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

and in vuex repository:

 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 script here : you can see the passed parameter in the warning :)


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 that it takes the passed args and puts them as the second argument to the submit function.

+7
source

Source: https://habr.com/ru/post/1012804/


All Articles