使用vuex时如何更改状态中的name
可以通过在组件中调用commit方法来提交一个mutation,从而更改状态中的name。具体步骤如下:
- 在
store中定义一个mutation,用来更新name状态:
const store = new Vuex.Store({
state: {
name: 'John'
},
mutations: {
updateName(state, newName) {
state.name = newName
}
}
})
- 在组件中通过
mapMutations辅助函数将mutation映射到组件的methods中:
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['updateName']),
changeName() {
this.updateName('Jane')
}
}
}
- 在组件的
changeName方法中调用updateName方法,传入新的名字'Jane',从而触发mutation,更新name状态。
这样就可以通过commit方法来更改状态中的name了
原文地址: https://www.cveoy.top/t/topic/hhVV 著作权归作者所有。请勿转载和采集!