vuex实现及简略解析(小结)

2020-06-13 10:34:48易采站长站整理

this.getters = {}
this.mutations = {}
this.actions = {}
// vuex的核心就是借用vue的实例,因为vuex的数据更改回更新视图
this._vm = new Vue({
data: {
state
}
})
// 循环getters的对象
myforEach(getters, (getterName, getterFn) => {
// 对this.getters对象进行包装,和vue的computed是差不多的
// 例如 this.getters['newCount'] = fn(state)
// 执行 this.getters['newCount']()就会返回计算的数据啦
Object.defineProperty(this.getters, getterName, {
get: () => getterFn(state)
})
})
// 这里是mutations各个key和值都写到,this.mutations对象上面
// 执行的时候就是例如:this.mutations['change']()
myforEach(mutations, (mutationName, mutationsFn) => {
// this.mutations.change = () => { change(state) }
this.mutations[mutationName] = () => {
mutationsFn.call(this, state)
}
})
// 原理同上
myforEach(actions, (actionName, actionFn) => {
// this.mutations.change = () => { change(state) }
this.actions[actionName] = () => {
actionFn.call(this, this)
}
})
const {commit , dispatch} = this // 先存一份,避免this.commit会覆盖原型上的this.commit
// 解构 把this绑定好
// 通过结构的方式也要先调用这类,然后在下面在调用原型的对应函数
this.commit = type => {
commit.call(this, type)
}
this.dispatch = type => {
dispatch.call(this, type)
}
}
get state() { // Object.defineProperty 同理
return this._vm.state
}
// commi调用
commit (type) {
this.mutations[type]()
}
// dispatch调用
dispatch (type) {
this.actions[type]()
}
}

通过上面的,我们可以看出,其实

mutations
actions
都是把传入的参数,赋值到
store
实例上的
this.mutations
this.actions
对象里面。

当组件中

this.$store.commit('change')
的时候 其实是调用
this.mutations.change(state)
,就达到了改变数据的效果,
actions
同理。

getters是通过对

Object.defineProperty(this.getters, getterName, {})

对this.getters进行包装当组件中
this.$store.getters.newCount
其实是调用
getters
对象里面的
newCount(state)
,然后返回计算结果。就可以显示到界面上了。