Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:
应用层级的状态应该集中到单个 store 对象中。
提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
异步逻辑都应该封装到 action 里面。
state [type: Object]
const store = new Vuex.Store({
state: {
count: 1
}
mutations: ...
})
modules
const moduleA = {
state,
mutations,
actions, // 可无
getters, // 可无
modules // 可无, 可嵌套
}
const moduleB = {
state,
mutations,
actions,
getters
modules
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a; // -> moduleA 的状态
store.state.a; // -> moduleB 的状态
getter
const store = new Vuex.Store({
state: { ... },
getter: {
exampleGetter(state, getters) {
return
}
}
})
const module = {
state: ...
getter: {
exampleGetter(state, getters, rootState)
}
}
mutations [type: string]: Function
// like Reducer
const store = new Vuex.Store({
...
mutations: {
increment (state, playload) {
// 变更状态
state.count++
}
}
})
mutation 必须是同步函数
devtools 不知道什么时候回调函数实际上被调用 —— 实质上任何在回调函数中进行的的状态的改变都是不可追踪的
actions
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象?
支持异步:
- promise
- async / await
function (context) {}
context = { state, rootState, getters, commit, dispatch}