let Vue;
class Sstore {
constructor(options) {
this.mutations = options.mutations;
this.actions = options.actions;
this._getters = options.getters;
this.getters = {};
const computed = {};
const that = this;
Object.keys(this._getters).forEach((key) => {
const fn = that._getters[key];
computed[key] = function() {
return fn(that.state);
};
Object.defineProperty(that.getters, key, {
get() {
return that._vm[key];
},
});
});
//把$$state变成响应时的方法,另一个方法:Vue.util.defineReactive
this._vm = new Vue({
data: {
$$state: options.state,
},
computed,
});
}
get state() {
return this._vm._data.$$state;
}
commit(type, payload) {
this.mutations[type](this.state, payload);
}
dispatch(type, payload) {
this.actions[type](this, payload);
}
}
function install(_vue) {
Vue = _vue;
//mixin可延迟执行代码,Vue.use(router)在new Vue 前,固此时$options无值
Vue.mixin({
beforeCreate() {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
},
});
}
export default {
Store: Sstore,
install: install,
};
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END