Vuex中修改store内存储数值的实现问题咨询
修正说明
- Vuex实例配置错误:Vuex要求mutation必须定义在
mutations根配置字段下,你之前直接将自定义的mutation集合作为根字段传入,导致Vuex无法识别对应mutation方法,commit调用会失效。 - mutation命名不符合需求:你需要调用名为
changeNumber的mutation,原代码将changeNumber作为mutation集合的变量名,集合内的实际mutation方法名为increment,不符合需求。 - 组件逻辑不符合需求:你需要的是点击p元素触发更新,原代码使用了input按钮,且根组件未引入计数器组件,无法看到对应效果。
完整可运行代码
let object = { } let state = { object, someArray: [], someBool: true, counter: 0, someOtherValue: 'Text' } // 定义mutation集合,方法名即为mutation的调用名 const mutations = { changeNumber(state) { state.counter += 1 } } let store = new Vuex.Store({ // 挂载mutation集合到指定配置项 mutations, state }) Vue.component('counter-button', { computed: { counter() { return this.$store.state.counter } }, // 替换为p元素,点击触发名为changeNumber的mutation,同时实时展示counter值 template: `<p @click="$store.commit('changeNumber')">{{ counter }}</p>` }) Vue.component('some-component', { computed: { someOtherValue() { return this.$store.state.someOtherValue } }, template: '<div>{{ someOtherValue }}</div>' }) new Vue({ el: '#app', store, // 根模板引入计数器组件 template: ` <div> <some-component></some-component> <counter-button></counter-button> </div> ` })
内容的提问来源于stack exchange,提问作者user15671949
相关产品推荐
相关产品推荐

