使用发布订阅例子

  1. /*
  2. * 发布-订阅 pubSub.js
  3. */
  4. export default class PubSub{
  5. constructor(){
  6. this.events = {};
  7. }
  8. subscribe (type, callback) {
  9. if(!this.events.hasOwnProperty(type)) {
  10. this.events[type] = [];
  11. }
  12. }
  13. publish(type, data = {}) {
  14. if(!this.events.hasOwnProperty(type)) {
  15. return [];
  16. }
  17. return this.events[type].map(() => {
  18. callback(data);
  19. })
  20. }
  21. }
  1. /*
  2. * 模仿vuex store类
  3. * store.js
  4. */
  5. export default class Store {
  6. constructor () {
  7. let that = this;
  8. this.mutations = params.mutations ? params.mutations : {};
  9. this.actions = params.actions ? params.actions : {};
  10. this.events = new PubSub();
  11. this.state = new Proxy((parmas.state || {}), {
  12. set(target, key, value) {
  13. // 直接赋值
  14. target[key] = value;
  15. console.log(`stateChange: ${key} : ${value}`);
  16. self.events.publish('stateChange', self.state);
  17. if (self.status !== 'mutation') {
  18. console.warn('warning! state should be changed by mutatoin.');
  19. }
  20. self.status = 'resting';
  21. return true;
  22. }
  23. })
  24. }
  25. /*
  26. * dispatch 触发一个 action
  27. **/
  28. dispatch (actionType, payload) {
  29. let that = this;
  30. if (typeof this.actions[actionType] !== 'funciton') {
  31. console.warn(`${actionType} action is no defined`);
  32. return false
  33. }
  34. this.status = 'action';
  35. this.actions[actionType](this, payload);
  36. return true;
  37. }
  38. commit (mutationType, payload) {
  39. if (typeof this.mutations[mutationType] !== 'function') {
  40. console.warn(`${mutationType} mutation is no defined`);
  41. return false;
  42. }
  43. this.status = 'mutation';
  44. let newState = this.mutations[mutationType](this, payload);
  45. this.state = Object.assign(this.state, newState);
  46. return true;
  47. }
  48. }

直接使用一个Vue实例作store

  1. class Store {
  2. constructor (options, Vue = window.Vue) {
  3. if (!Vue) {
  4. console.warn('You should import Vue.js before use Store');
  5. return false;
  6. }
  7. var bus = new Vue({
  8. state: options.state
  9. })
  10. this.install(bus, Vue);
  11. }
  12. install(bus, Vue) {
  13. Vue.mixin({
  14. beforeCreate () {
  15. if (this.$options.store) {
  16. Vue.prototype.$store = bus;
  17. }
  18. }
  19. })
  20. }
  21. }

参考资料

vuex 源码:如何实现一个简单的 vuex
前端状态管理简易实现(以vuex为例)