实现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
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值