使用发布订阅例子
/*
* 发布-订阅 pubSub.js
*/
export default class PubSub{
constructor(){
this.events = {};
}
subscribe (type, callback) {
if(!this.events.hasOwnProperty(type)) {
this.events[type] = [];
}
}
publish(type, data = {}) {
if(!this.events.hasOwnProperty(type)) {
return [];
}
return this.events[type].map(() => {
callback(data);
})
}
}
/*
* 模仿vuex store类
* store.js
*/
export default class Store {
constructor () {
let that = this;
this.mutations = params.mutations ? params.mutations : {};
this.actions = params.actions ? params.actions : {};
this.events = new PubSub();
this.state = new Proxy((parmas.state || {}), {
set(target, key, value) {
// 直接赋值
target[key] = value;
console.log(`stateChange: ${key} : ${value}`);
self.events.publish('stateChange', self.state);
if (self.status !== 'mutation') {
console.warn('warning! state should be changed by mutatoin.');
}
self.status = 'resting';
return true;
}
})
}
/*
* dispatch 触发一个 action
**/
dispatch (actionType, payload) {
let that = this;
if (typeof this.actions[actionType] !== 'funciton') {
console.warn(`${actionType} action is no defined`);
return false
}
this.status = 'action';
this.actions[actionType](this, payload);
return true;
}
commit (mutationType, payload) {
if (typeof this.mutations[mutationType] !== 'function') {
console.warn(`${mutationType} mutation is no defined`);
return false;
}
this.status = 'mutation';
let newState = this.mutations[mutationType](this, payload);
this.state = Object.assign(this.state, newState);
return true;
}
}
直接使用一个Vue实例作store
class Store {
constructor (options, Vue = window.Vue) {
if (!Vue) {
console.warn('You should import Vue.js before use Store');
return false;
}
var bus = new Vue({
state: options.state
})
this.install(bus, Vue);
}
install(bus, Vue) {
Vue.mixin({
beforeCreate () {
if (this.$options.store) {
Vue.prototype.$store = bus;
}
}
})
}
}
参考资料
vuex 源码:如何实现一个简单的 vuex
前端状态管理简易实现(以vuex为例)