I want to set Vuex mutations as follows:
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel: `${this.store}/changeModel`
})
}
}
But I catch the error:
Uncaught TypeError: Cannot read property 'store' of undefined
How do I correctly use props inside the module mutation name?
I want to map this.$storemit('form1/changeModel')
, where form1
is set from props.
I want to set Vuex mutations as follows:
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel: `${this.store}/changeModel`
})
}
}
But I catch the error:
Uncaught TypeError: Cannot read property 'store' of undefined
How do I correctly use props inside the module mutation name?
I want to map this.$store.mit('form1/changeModel')
, where form1
is set from props.
-
1
What's wrong with
...mapMutations(['changeModel'])
? Do you want to mapthis.$store.mit('changeModel')
- or something else? – raina77ow Commented Aug 29, 2018 at 20:07 -
2
I want to map
this.$store.mit('form1/changeModel')
, whereform1
is set from props. – mcmimik Commented Aug 29, 2018 at 20:16 - 2 @mcmimik Why are you using mutations directly in your ponent instead of actions to begin with? – Bennett Dams Commented Sep 5, 2018 at 15:18
- 1 @BennettDams You're right, actions should be used here. – mcmimik Commented Sep 11, 2018 at 23:57
3 Answers
Reset to default 3 +100Vuex helper mapMutations
can be used with a function which works with this
.
There does not seem to be a doc for this, but the Vuex unit test helpers.spec.js illustrates the pattern.
const vm = new Vue({
store,
methods: mapMutations({
plus (mit, amount) {
mit('inc', amount + 1)
}
})
})
As a bonus, the function allows passing a parameter to the mutation, which is a mon requirement.
Your code changes would be:
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel(mit) { mit(`${this.store}/changeModel`) }
})
}
}
The call within your ponent is just changeModel()
- mapMutations is taking care of injecting the mit
parameter.
Note, I am not sure this is adding much except some extra noise (pared to a simple this.$store.mit()
), but perhaps your requirement is more plicated than the example code.
I think there is no way to bind this on mapActions. But you can call it with $store.dispatch
methods: {
changeModel() {
this.$store.dispatch(`${this.store}/changeModel`);
}
}
It is not exaclty the solution that you asked but its effect is the same. As the mutation is a variable parameter, it is obvious to put it into a function as an input parameter instead of changing the mutation name. I would create an action in the store like this:
changeModel ({dispatch, mit, rootGetters}, mutationName) {
mit(`${mutationName}/changeModel`, {}, {root: true})
})
And I would use this action in the ponent passing the mutationName into it.