Vuex 基本结构
Vuex 是 Vue 的一个插件,需要使用 Vue.use 调用。Vue 的插件是一个函数或者是一个对象包含 install 方法,Vue.use 的作用就是去执行这个函数或者 install 方法给 Vue 实例添加这个插件。所以 Vuex 是一个包含 install 方法的对象。
另外,Vuex 还会通过 new Vuex.store 的方式实例一个仓库,所以,Vuex 插件这个对象除了 install 方法之外应该还包含一个 store 构造函数或者类。
所以 Vuex 的基本结构为:
let _Vue = null
class Store {}
function install (Vue) {
_Vue = Vue
}
export default {
Store,
install
}
install
在 install 中需要把创建 Vue 实例的时候,传入的 store 对象注入到 Vue 原型上的 s t o r e , 在 所 有 的 组 件 中 都 可 以 使 用 t h i s . store ,在所有的组件中都可以使用 this. store,在所有的组件中都可以使用this.store 获取 Vuex 的仓库,从而实现,在所有组件中共享状态。因为在 install 中获取不到 Vue 的实例,所以需要通过混入 beforeCreate 来获取 Vue 实例,从而获取到选项中的 store 对象。
完整代码
let _Vue = null
class Store {
constructor (options) {
const {
state = {},
getters = {},
mutations = {},
actions = {}
} = options
this.state = _Vue.observable(state)
this.getters = Object.create(null)
Object.keys(getters).forEach(key => {
console.log(this.getters)
Object.defineProperty(this.getters, key, {
get: () => getters[key](state)
})
})
this._mutations = mutations
this._actions = actions
}
commit (type, payload) {
this._mutations[type](this.state, payload)
}
dispatch (type, payload) {
this._actions[type](this, payload)
}
}
function install (Vue) {
_Vue = Vue
_Vue.mixin({
beforeCreate () {
if (this.$options.store) {
// 如果是组件实例,没有 store 选项,就不需要执行下面的步骤
_Vue.prototype.$store = this.$options.store
}
}
})
}
export default {
install,
Store
}
562

被折叠的 条评论
为什么被折叠?



