最简单的 Store
安装 Vuex
之后,让我们来创建一个 store
。创建过程直截了当——仅需要提供一个初始 state
对象和一些 mutation
:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
state.count++
}
}
})
通过 store.state
来获取状态对象,以及通过 store.commit
方法触发状态变更:
store.commit('add')
console.log('store.state.count:' + store.state.count) // -> store.state.count:1
为了在 Vue 组件中访问 this.$store property
,你需要为 Vue
实例提供创建好的 store
。Vuex
提供了一个从根组件向所有子组件,以 store
选项的方式 注入 该 store
的机制:
// main.js
new Vue({
el: '#app',
store
})
现在我们可以从组件的方法提交一个变更,进而修改 state
中的 count
变量值:
methods: {
add() {
this.$store.commit('add')
console.log('state.count' + this.$store.state.count)
}
}
为什么用 mutation 方式修改 state 中定义的变量,而不是直接修改
-
我们通过提交
mutation
的方式,而非直接改变store.state.count
,是因为我们想要更明确地追踪到状态的变化。 -
这个简单的约定能够让你的意图更加明显,这样你在阅读代码的时候能更容易地解读应用内部的状态改变。
-
此外,这样也让我们有机会去实现一些能记录每次状态改变,保存状态快照的调试工具。
由于 store
中的状态是响应式的,在组件中调用 store
中的状态简单到仅需要在计算属性中返回即可。触发变化也仅仅是在组件的 methods
中提交 mutation
。