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

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

到这里我们使用

vuex
创建了一个
store
,并且在我们的App组件视图中使用,但是我们会有一些列的疑问。

store
是如何被使用到各个组件上的??
为什么
state
的数据是双向绑定的??
在组件中为什么用
this.$store.dispch
可以触发
store
actions
??
在组件中为什么用
this.$store.commit
可以触发
store
mutations
??
….等等等等

带着一堆问题,我们来自己实现一个

vuex
,来理解
vuex
的工作原理。

安装并使用store

src
下新建一个
vuex.js
文件,然后代码如下


'use strict'

let Vue = null

class Store {
constructor (options) {
let { state, getters, actions, mutations } = options
}
}
// Vue.use(Vuex)
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 }

然后修改

store.js
中的引入vuex模块改成自己的vuex.js

import Vuex from './vuex' // 自己创建的vuex文件

在我们的代码中

export default { install, Store }
导出了一个对象,分别是
install
Store

install
的作用是,当
Vue.use(Vuex)
就会自动调用
install
方法,在
install
方法里面,我们用
mixin