在 Vuex 中,我的突变对象如下:
mutations: {
someMethod(){
this.someReusableCode();
},
anotherMethod(){
this.someReusableCode();
},
someReusableCode(){
...
}
}
但是,我收到一个错误,提示未定义 someReusableCode()
。哪里是定义我的 someReusableCode()
方法的最佳位置,这样它才能工作?
最佳答案
你可以在 store
对象(Vuex.Store
的实例)之外定义一个共享方法。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) { this.inc(state) },
decrement(state) { this.dec(state) }
}
})
// Shared functions of store
store.inc = state => state.count++;
store.dec = state => state.count--;
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) { this.inc(state) },
decrement(state) { this.dec(state) }
}
})
// Shared functions: inc() and dec()
store.inc = state => state.count++
store.dec = state => state.count--
new Vue({
el: '#app',
computed: {
count() {
return store.state.count
}
},
methods: {
increment () {
store.commit('increment')
},
decrement () {
store.commit('decrement')
}
}
})
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<div id="app">
<p>{{ count }}</p>
<p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
</div>
关于javascript - 用于突变的 Vuex 辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48219418/