实现vuex的commit与dispatch

实现vuex的commit与dispatch

//定义一个Vue  而不是直接导入vue   减少内存占用
let Vue;

class Store {
          
   
  constructor(options) {
          
   
    this._mutations = options.mutations
    this._actions = options.actions
    //直接使用this.state创建实例的话  方法不安全   在外部可以直接访问并进行存取
    // this.state = new Vue({
          
   
    //   data: options.state
    // })

    //所以使用$$state的方法   这时候进行读取的话  就要使用get state()进行读取
    this._vm = new Vue({
          
   
      data: {
          
   
        // 加两个$$   因为vue不做代理   这样可以使外部不能直接读取这个state
        $$state: options.state
      }
    })

    this.commit = this.commit.bind(this)
    this.dispatch = this.dispatch.bind(this)
  }

  // 使用存取器就能读取到state了
  get state() {
          
   
    return this._vm.data.$$state
  }

  // 当用户进行set时
  set state(v) {
          
   
    console.error(不能直接修改state中的值)
  }

  // 使用commit方法是可以传递两个参数   一个为方法类型   另一个为载荷(参数)
  commit(type, payload) {
          
   //type是从mutations中提取的方法
    const entry = this._mutations[type]
    if (entry) {
          
   //如果有这个方法就执行
      entry(this.state, payload)//方法执行有两个参数  一个state   另一个为payload
    }
  }

  dispatch(type, payload) {
          
   
    const entry = this._actions[type]//action中第一个参数为{commit}  是可以结构的  说明传过去的是这个store类
    if (entry) {
          
   //如果有这个方法就执行
      entry(this, payload)//方法执行有两个参数  一个state   另一个为payload
    }
  }
}
//当使用install时vue会自动解析并把vue传入
function install(_Vue) {
          
   
  Vue = _Vue
  //利用混入的方法
  Vue.mixin({
          
   
    beforeCreate() {
          
   
      if (this.$options.store) {
          
   
        Vue.prototype.$store = this.$options.store
      }
    }
  })
}

export default {
          
   
  Store,
  install
}
经验分享 程序员 微信小程序 职场和发展