Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式和库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装
首先,你需要安装 Vuex。你可以通过 npm 或 yarn 来安装:
npm install vuex --save
# 或者
yarn add vuex
初始化
在 Vue 应用程序中创建一个 Vuex 实例:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 初始状态
},
mutations: {
// 改变状态的函数
},
actions: {
// 提交 mutation 的函数
},
getters: {
// 从 state 中派生出一些状态
}
})
使用
在组件中使用 Vuex:
// 创建一个 Vue 实例
new Vue({
el: '#app',
store,
render: h => h(App)
})
示例
假设我们有一个计数器应用,我们可以这样使用 Vuex:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
}
})
// 在组件中
computed: {
count() {
return this.$store.state.count
}
},
methods: {
increment() {
this.$store.dispatch('increment')
}
}
Vuex 示例
更多关于 Vuex 的信息,请访问 Vuex 官方文档
注意事项
- Vuex 应该被用于中大型应用,而不是所有大小的应用。
- Vuex 的状态是响应式的,这意味着当状态发生变化时,所有依赖于这个状态的组件都将得到更新。
- Vuex 的设计目标是实现集中式存储管理,因此不要在组件内部直接修改状态。
希望这个快速开始指南能帮助你入门 Vuex。更多高级功能和最佳实践,请参阅 Vuex 官方文档。