You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 12:21:01