Vuex原理篇
1. 设计思路
- 统一状态存储 store,state为响应式的
- 可预测变更,唯一修改途径 store.commit()
2. 创建Store实例
1. 插件方法
store.install = function(app) {
const store = this
app.config.globalProperties.$store = store
}
2. state为响应式的
const store = {
_state: reactive(options.state())
}
3. 不能随意修改state
Object.defineProperty(store, 'state', {
get state() {
return this._state
},
set state(v) {
console.error('please use replaceState() to reset state')
}
})
4. 唯一修改途径 commit()
const store = {
...
_mutations: options.mutations,
}
fuction commit(type, payload) {
const entry = this._mutations[type]
if(!entry) {
console.error(`unknown mutation type: ${type}`)
return
}
entry.call(this.state, this.state, payload)
}
store.commit = commit.bind(store)
5. 异步处理 dispatch()
const store = {
...
_actions: options.actions,
}
function dispatch(type, payload) {
const entry = this._actions[type]
if(!entry) {
console.error(`unknown dispatch type: ${type}`)
return
}
return entry.call(this, this, payload)
}
store.dispatch = commit.dispatch(store)
5. 计算属性 getters
store.getters = {}
Object.keys(options.getters).forEach((key) => {
const result = computed(() => {
const getter = options.getters[key]
if(getter) {
return getter.call(store, store.state)
} else {
console.error('unknown getter type:' + type)
return ''
}
})
Object.defineProperty(store.getters, key, {
get() {
return result
}
})
})