什么是 Vuex?
Vuex 是 Vue .js 应用程序的状态管理模式 + 库。它充当应用程序中所有组件的集中式存储,其规则确保状态只能以可预测的方式进行更改。
如果您从未构建过大型SPA并直接跳入Vuex,它可能会感到冗长和令人生畏。这是完全正常的 - 如果你的应用程序很简单,那么建议不需要使用Vuex!
安装
npm install vuex@next --save
yarn add vuex@next --save
开始
1.整个store文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
2 state 状态?
//作为vuex储存数据的地方
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
2.1 组件引用state
$store.state.todos
3 getters 您可以将它们视为存储的计算属性
//装饰 类似于计算属性
getters: {
// ...
doneTodosCount (state, getters) {
return getters.doneTodos.length
}
}
3.1调用getters
store.getters.doneTodosCount
4 mutations 突变
//处理程序函数是我们执行实际状态修改的地方,它将接收状态作为第一个参数:
mutations: {
increment (state) {
// mutate state
state.count++
}
}
3.1mutations 传参
mutations: {
increment (state, n) {
state.count += n
}
}
3.2调用mutations
store.commit('increment',5)
4.actions 行动
操作不会改变状态,而是提交突变。
操作可以包含任意异步操作。
//在实践中,我们经常使用ES2015参数解构来简化代码(特别是当我们需要多次调用时):commit
actions: {
increment ({ commit }) {
commit('increment')
}
}
actions: {
//不解构的时候context 指向mutations
increment (context) {
context.commit('increment')
}
}
4.1调用actions
this.$store.dispatch('xxx')
mapActions
store.dispatch
store