可以通过在组件中调用 'commit' 方法来提交一个 'mutation',从而更改状态中的 'name'。具体步骤如下:

  1. 在 'store' 中定义一个 'mutation',用来更新 'name' 状态:
const store = new Vuex.Store({
  state: {
    name: 'John'
  },
  mutations: {
    updateName(state, newName) {
      state.name = newName
    }
  }
})
  1. 在组件中通过 'mapMutations' 辅助函数将 'mutation' 映射到组件的 'methods' 中:
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations(['updateName']),
    changeName() {
      this.updateName('Jane')
    }
  }
}
  1. 在组件的 'changeName' 方法中调用 'updateName' 方法,传入新的名字 'Jane',从而触发 'mutation',更新 'name' 状态。

这样就可以通过 'commit' 方法来更改状态中的 'name' 了。

Vuex 状态管理:如何更改 name 属性

原文地址: https://www.cveoy.top/t/topic/oKNA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录