参考element-ui的自定义Store

2018-08-29  本文已影响0人  令狐铁蛋

基本框架:这是一个Vuex的组件级的解决方案

  1. 解决父子,兄弟组件的通信问题
  2. 解决Vuex的单例问题,因为Vuex是单例的,所以需要重复使用的组件不应该依赖Vuex,会造成多个实例公用一套状态
const Store = function (initialState = {}) {
    this.state = {
        loading: true
    };

    Object.assign(this.state, initialState);
}

Store.prototype.mutations = {
    async loadstart(state) {
        state.loading = true;
    },
    async loadend(state) {
        state.loading = false;
    }
};

Store.prototype.commit = function (name, ...args) {
    const mutations = this.mutations;
    if (mutations[name]) {
        return mutations[name].apply(this, [this.state].concat(args));
    } else {
        throw new Error(`Action not found: ${name}`);
    }
};

export default Store;

上一篇 下一篇

猜你喜欢

热点阅读