vuex的简单实现方式

vuex的响应式是数据是通过vue的响应式来实现的,也就是使用公共总线的方式,

import Vue from 'vue';

export class Store {
  constructor(options = {}) {
    // 可以利用vue数据的响应,
    this._vm = new Vue({
      data: {
        $store: options.state
      }
    });
    this.state = this._vm._data.$store;
    this.actions = options.actions;
    this.mutations = options.mutations;
    const { dispath, commit } = this;
    // 重写,可以再里面做一些验证什么的,自由发挥
    this.dispath = (type, payload) => dispath.call(this, type, payload); // 重写为action注入commit
    this.commit = (type, payload) => commit.call(this, type, payload);

  }
  dispath(type, payload) {
    const actionParams = { type, payload, commit: this.commit };
    const action = this.actions[type];
    if (!action) {
      console.error(`[vuex] unknown action type: ${type}`);
      return
    }
    action(actionParams);
  }

  commit(type, payload) {
    const mutation = this.mutations[type];
    if (!mutation) {
      console.error(`[vuex] unknown mutation type: ${type}`);
      return
    }
    this.isCommit = true;
    mutation(this.state, payload);
    this.isCommit = false;
  }
}

export function install(Vue) {
  Vue.mixin({ beforeCreate: vuexInit })
}

function vuexInit() {
  const options = this.$options;// 在new Vue的时候传进去的键值对都可以在this.$options里面找到
  if (options.store) {
    this.$store = options.store
  } else if (options.parent && options.parent.$store) {
    this.$store = options.parent.$store
  }
}

export default {
  Store,
  install,
  version: '__VERSION__',
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。