simple vuex

114 阅读1分钟
let Vue;
class Store{
  constructor(option){
    this.options = option;
    // 第一步 使得state 可响应式 Vue.util.defineReactive defineReactive
    Vue.util.defineReactive(this,'state',option.state);
    // 将getters、mutatios action 方法添加到当前实例中
    this.getters = resolvegetters(this);
    this.commit = resolveCommit.bind(this);
    this.dispatch = resolveDispatch.bind(this);
  }
}
const resolvegetters = (vm)=>{
  let obj = Object.create(null);
  let keys = Object.keys(vm.options.getters);
  keys.forEach((value)=>{
    obj[value] = vm.options.getters[value].call(vm,vm.state)
  })
  return obj;
}
function resolveCommit (type, rest){
  console.log(this);
  this.options.mutations[type](this.state, rest);
}
function resolveDispatch (type, rest){
  this.options.actions[type](this, rest);
}
const install = (_Vue) => {
  // 把
  Vue = _Vue;
  //将$store 混入每个组件
  Vue.mixin({
    beforeCreate(){
      if(this.$options.store){
          this.$store = this.$options.store
      }else{
          this.$store = this.$parent &&  this.$parent.$store;
      }
    }
  })
}
export default {
  Store,
  install
}