简单的vuex实现

实现一个vuex插件
pvuex 初始化: Store声明、install实现,vuex.js:

let Vue;
// 定义install方法 完成赋值与注册
function install(_Vue) {
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store;
      }
    }
  });
}
// 定义sotre类,管理响应式状态 state
class Store {
  constructor(options = {}) {
    this._vm = new Vue({
      data: {
        $$state:options.state
      }
    }); 
  }
  get state() {
    return this._vm._data.$$state
  }
  set state(v) {
    return v
  } 
}
function install(_Vue) {
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store;
      }    
    }
  }); 
}

 
export default { Store, install };

实现 commit :根据用户传入type获取并执行对应 mutation

 
// class Store...
  constructor(options = {}) {
    // 保存用户配置的mutations选项
    this._mutations = options.mutations || {}
  }
  commit(type, payload) {
    // 获取对应的mutation
    const entry = this._mutations[type]
    // 传递state给mutation 
    entry && entry(this.state, payload);
  } 

实现 actions :根据用户传入type获取并执行对应 action

constructor(options = {}) {
    this._actions = options.actions || {}

    const store = this
    const {commit, action} = store
    // 将上下文指定为sotre实例
    this.commit = this.commit.bind(this)
    this.dispatch = this.dispatch.bind(this)
}
dispatch(type, payload) {
    // 获取对应的action
    const entry = this._actions[type]
 
    return entry && entry(this, payload);
}

实现 getters , 并利用computed属性缓存.

// class Store

 const store = this
 const computed = {}
 Object.keys(this._getters).forEach(key => {
     computed[key] = function(){
        store._getters[key](store.state)
    }    
    Object.defineProperty(this.getters, key, {
        get(){
            return store._vm[key]
        },
        set(v){
            console.log(v)
        }
    })
 });
 this._vm = new Vue({
     data: {
         $$state:options.state
     },
     computed
 });     

你可能感兴趣的:(vuex)