我可以使用"this"吗?在mapMutations中传播在Vue实例方法内部? [英] Can I use "this" in mapMutations spread inside Vue instance methods?
问题描述
我要设置Vuex突变如下:
I want to set Vuex mutations as follows:
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel: `${this.store}/changeModel`
})
}
}
但是我发现了错误:
未捕获的TypeError:无法读取未定义的属性存储"
Uncaught TypeError: Cannot read property 'store' of undefined
如何在模块突变名称中正确使用 props ?
How do I correctly use props inside the module mutation name?
我想映射this.$store.commit('form1/changeModel')
,其中form1
是通过 props 设置的.
I want to map this.$store.commit('form1/changeModel')
, where form1
is set from props.
推荐答案
Vuex帮助程序mapMutations
可以与与this
一起使用的函数一起使用.
Vuex 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 (commit, amount) {
commit('inc', amount + 1)
}
})
})
作为奖励,该函数允许将参数传递给突变,这是常见的要求.
As a bonus, the function allows passing a parameter to the mutation, which is a common requirement.
您的代码更改为:
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel(commit) { commit(`${this.store}/changeModel`) }
})
}
}
您组件中的调用只是changeModel()
-mapMutations负责注入commit
参数.
The call within your component is just changeModel()
- mapMutations is taking care of injecting the commit
parameter.
请注意,除了一些额外的噪音(与简单的this.$store.commit()
相比),我不确定这会增加多少,但也许您的要求比示例代码更复杂.
Note, I am not sure this is adding much except some extra noise (compared to a simple this.$store.commit()
), but perhaps your requirement is more complicated than the example code.
这篇关于我可以使用"this"吗?在mapMutations中传播在Vue实例方法内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!