- 实现一个插件:挂载 $store
- 实现store
以下是实现的一份简易版 vuex 源码:
// 一、缓存Vue构造函数
let Vue;
// 二、核心:声明一个Store类
class Store {
constructor(options) {
//访问state方法:this.$store.state.xxx
this._vm = new Vue ({
// Vue会把data里的数据变为响应式,
// 在这里给state做响应式处理
// 用一个方法将这个state暴露到外边,
// 将new Vue ( )赋值给一个变量,this.state
data: {
$$state: options.state
}
})
this.mutations = options.mutations
this.actions = options.actions
this.commit = this.commit.bind