Daotin's Blog

  1. min-vuex.js
  2. 使用

min-vuex.js

import Vue from 'vue'

// 实现在store.js中可以使用Vue.use(Vuex);,否则只能使用Vue.prototype.$store = store
function install () {
  function vuexInit () {
    var options = this.$options; // $option 是用来获取data外面的数据和方法
    
    if (options.store) {
      this.$store = typeof options.store === 'function' ? options.store() : options.store;
    } else if (options.parent &&  options.parent.$store) {
      this.$store = options.parent.$store;
    }
  }
  // 混入
  Vue.mixin({ beforeCreate: vuexInit });
}

// 实现vuex的获取state,commit,getter功能
const Store = function Store(options = {}) {
    let { state = {}, mutations = {}, getters = {} } = options;

    const computed = {}
    const store = this
    store.getters = {};
    
    for (let [key, fn] of Object.entries(getters)) {
        // 通过store传入的getters构建vm实例的computed,然后才能取到其中的值。
        computed[key] = function() {
            // 第一个参数为state,第二个参数为其他getters,
            // 第二个参数的作用是循环的时候,第一次 store.getters对象为空,然后通过Object.defineProperty不停添加属性
            return fn(store.state, store.getters); 
        };
        // 取值的时候,computed的属性就是vm的属性,直接取即可
        Object.defineProperty(store.getters, key, {
            get: function() {
                return store._vm[key];
            },
        });
    }
    // 实现state的核心代码,就是讲state放入vue实例的data中
    this._vm = new Vue({
        data: {
            $$state: state,
        },
        computed
    });
    this._mutations = mutations;
}

// 实现this.$store.commit
Store.prototype.commit = function(type, payload) {
    if (this._mutations[type]) {
        this._mutations[type](this.state, payload)
    }
}

// 实现获取state数据
Object.defineProperties(Store.prototype, {
    state: {
        get: function() {
            return this._vm.$data.$$state
        }
    },
})

export default { Store, install }

使用

在store.js中可以导入use。其他与正宗Vuex无异。

import Vuex from './min-vuex.js'
Vue.use(Vuex);

(完)