3-3-04-Vuex基本实现

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值