学习优先度:★★★★★
难易度:★★☆☆☆
Vuex 为管理 Vue.js 应用程序的状态提供了一个集中式存储空间,使处理复杂数据流变得更加容易。
下面是一个设置 Vuex 存储的基本示例:
【代码示例】
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCount: state => state.count * 2
}
})
// In a component
export default {
computed: {
count() {
return this.$store.state.count
},
doubleCount() {
return this.$store.getters.doubleCount
}
},
methods: {
increment() {
this.$store.commit('increment')
},
incrementAsync() {
this.$store.dispatch('incrementAsync')
}
}
}
【执行结果】
现在,该组件可以访问和修改集中状态,这些更改将反映在使用该状态的所有组件中。
Vuex 使用单一状态树,这意味着所有应用程序级状态都包含在一个对象中。这使得调试和随时了解应用程序的状态变得更加容易。
存储由几个部分组成:
state: 存储中的实际数据。
mutations: 直接改变状态的函数。这些函数必须是同步的。
actions: 提交突变的函数。可以是异步的。
getters: 存储的计算属性。
在组件中,我们使用计算属性来访问状态和获取器。要修改状态,我们使用 commit() 调用突变,或使用 dispatch() 调度操作。
这种集中式方法有助于管理复杂的状态交互,并通过分离状态管理的逻辑使组件更简洁。
【补充】
Vuex 还支持模块,允许您将存储分成更小、更易于管理的部分。这对于具有复杂状态管理需求的大型应用程序尤其有用。