
到这里我们使用
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










