白手撸一个vuex

154 阅读1分钟

大体框架

let _Vue = null;
// 用于定义state,action之类的
class Store {
	...
}

// 给vue注入store用的
function install (Vue) {
	...
}

补全install方法

function install (Vue) {
  _Vue = Vue // 这里的_Vue是为了获取Vue,并可全局使用
  _Vue.mixin({
    beforeCreate () { // 这里是给的vue实例混入beforeCreate方法
      if (this.$options.store) { // 一般组件实例没有store,这里是在页面入口new Vue(...app)后,会触发到beforeCreate钩子
        _Vue.prototype.$store = this.$options.store
      }
    }
  })
}

补全Store类

class Store {
  constructor (options) {
    const {
      state = {},
      getters = {},
      mutations = {},
      actions = {}
    } = options
    this.state = _Vue.observable(state) // state需要是响应式的
    this.getters = Object.create(null)
    Object.keys(getters).forEach(key => {
      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)
  }
}

至此,一个vuex就撸完了,把项目里的 import Vuex from 'vuex'改成 import Vuex from '自己写的vuex文件地址',即可测试使用。使用例子和平常使用vuex一模一样,就不show code了。