Vuex 集中式存储管理应⽤的所有组件的状态,并以相应的规则保证状态以可预测的⽅式发⽣变化。
安装vuex
vue add vuex
核心概念:
state 状态、数据
mutations 更改状态的函数
actions 异步操作
store 包含以上概念的容器
状态 - state
export default new Vuex.Store({
state: { counter:0 },
})
状态变更 - mutations
export default new Vuex.Store({
mutations: {
add(state) {
state.counter++
}
}
})
派⽣状态 - getters
export default new Vuex.Store({
getters: {
doubleCounter(state) { // 计算剩余数量
return state.counter * 2;
}
}
})
动作 - actions
export default new Vuex.Store({
actions: {
add({ commit }) {
setTimeout(() => {
commit('add')
}, 1000);
}
}
})
原理解析:
实现Store类
维持⼀个响应式状态state
实现commit()
实现dispatch()
getters
挂载$store
要点:
初始化:Store声明、install实现,
let Vue;
class Store {
constructor(options = {}) {
this._vm = new Vue({
data: {
$$state:options.state
}
});
}
get state() {
return this._vm._data.$$state
}
set state(v) {
console.error('please use replaceState to reset state');
}
}
function install(_Vue) {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
}
});
}export default { Store, install };
实现commit:根据⽤户传⼊type获取并执⾏对应mutation
class Store {
constructor(options = {}) {
// 保存⽤户配置的mutations选项
this._mutations = options.mutations || {}
}
commit(type, payload) {
// 获取type对应的mutation
const entry = this._mutations[type]
if (!entry) {
console.error(`unknown mutation type: ${type}`);
return
}
// 指定上下⽂为Store实例
// 传递state给mutation
entry(this.state, payload);
}
}
实现actions:根据⽤户传⼊type获取并执⾏对应action
class Store {
constructor(options = {}) {
// 保存⽤户编写的actions选项
this._actions = options.actions || {}
// 绑定commit上下⽂否则action中调⽤commit时可能出问题!!
// 同时也把action绑了,因为action可以互调
const store = this
const {commit, action} = store
this.commit = function boundCommit(type, payload) {
commit.call(store, type, payload)
}
this.action = function boundAction(type, payload) {
return action.call(store, type, payload)
}
}
dispatch(type, payload) {
// 获取⽤户编写的type对应的action
const entry = this._actions[type]web全栈架构师
if (!entry) {
console.error(`unknown action type: ${type}`);
return
}
// 异步结果处理常常需要返回Promise
return entry(this, payload);
}
}