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

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

get: () => {
return getterFn(rootModule.state)
}
})
})
}
// 在跟模块设置actions
if (rootModule._raw.actions) {
myforEach(rootModule._raw.actions, (actionName, actionsFn) => {
// 因为同是在根模块设置,子模块也有能相同的key
// 所有把所有的都放到一个数组里面
// 就变成了例如 [change, change] , 第一个是跟模块的actions的change,第二个是a模块的actions的change
let entry = store.actions[actionName] || (store.actions[actionName] = [])
entry.push(() => {
const commit = store.commit
const state = rootModule.state
actionsFn.call(store, {state, commit})
})
})
}
// 在跟模块设置mutations, 同理上actions
if (rootModule._raw.mutations) {
myforEach(rootModule._raw.mutations, (mutationName, mutationFn) => {
let entry = store.mutations[mutationName] || (store.mutations[mutationName] = [])
entry.push(() => {
mutationFn.call(store, rootModule.state)
})
})
}
// 递归遍历子节点的设置
myforEach(rootModule._children, (childName, module) => {
installModules(store, rootState, path.concat(childName), module)
})
}

const install = _Vue => {
// 避免vuex重复安装
if (Vue === _Vue) return
Vue = _Vue
Vue.mixin({
// 通过mixins让每个组件实例化的时候都会执行下面的beforeCreate
beforeCreate () {
// 只有跟节点才有store配置
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else if (this.$parent && this.$parent.$store) { // 子组件深度优先 父 --> 子---> 孙子
this.$store = this.$parent.$store
}
}
})
}

export default { install, Store }

看到代码以及注释,主要流程就是根据递归的方式,处理数据,然后根据传进来的配置,进行操作数据。

至此,我们把

vuex
的代码实现了一遍,在我们
App.vue
的代码里添加


<template>
<div id="app">
这里是store的state------->{{this.$store.state.count}} <br/>
这里是store的getter------->{{this.$store.getters.newCount}} <br/>
这里是store的state.a------->{{this.$store.state.a.count}} <br/>
<button @click="change">点击触发dispach--> actions</button>
<button @click="change1">点击触发commit---> mutations</button>
</div>
</template>

最后查看结果。

源码地址:https://github.com/naihe138/write-vuex