因为最近需要对原有项目进行改造,之前没有认真研究过vuex的使用,今天把学习官方文档的过程记录下来以供日后查阅,同时也希望能够为其他开发人员提供参考。
vuex的核心点是store,store本质上是一个仓库,它可以存储大部分的state。而这种存储是响应式的,如果state发生变化,那么对应的组件也会响应更新。如果想要改变state,那么需要通过commit mutation。
以下示例引用自官网(开始 | Vuex):
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
创建完成后可在vue组件中可以以this.$store.commit('具体mutation方法')来提交状态变更
然后通过this.$store.state.x具体某一statex来得到对象的内容。
如果想要更简便的从store实例中读取状态,可以直接在computed中返回某个状态:
// 创建一个 Counter 组件
const Counter = {
template: `<div>{
{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}