Vuex
Vuex
的核心是store
,store
包含着state(状态)
、getter(计算属性)
、mutation(事件)
、action(异步操作)
;
Vuex
类似一个全局变量,但有两个主要的区别:
- Vuex 的状态存储是响应式的
- 不能直接改变 store 中的状态,只能通过提交
mutation
来改变
state
保存着应用的状态
getter
类似于 Vue 应用中的 computed ,是从 store 中的 state 中派生出一些状态
mutation
更改 Vuex 的 store 中的状态的唯一方法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
store.commit('increment')
action
与 mutation 类似,不同在于:
- action 提交的是 mutation,而不是直接变更状态
- action 可以包含异步操作
module
复杂的应用需要区分不同的模块
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态