實現簡版Vuex

let Vue

const install = (_Vue) => {
  Vue = _Vue
  console.log('install')
  Vue.mixin({
    beforeCreate() {
      if (this.$options && this.$options.store) {
        this.$store = this.$options.store
      }
      else {
        this.$store = this.$parent && this.$parent.$store
      }
    },
  })
}

const forEach = (obj, cb) => {
  Object.keys(obj).forEach(key => {
    cb(key, obj[key])
  })
}

class Store {
  constructor(options = {}) {
    this.s = new Vue({ // 定義了state的響應式更新
      data() {
        return {
          state: options.state
        }
      }
    })

    let getters = options.getters;
    this.getters = {}
    forEach(getters, (getterName, fn) => {
      Object.defineProperty(this.getters, getterName, {
        get: () => {
          return fn(this.state)
        }
      })
    })

    let mutations = options.mutations;
    this.mutations = {}
    forEach(mutations, (mutationName, fn) => {
      this.mutations[mutationName] = (payload) => {
        fn(this.state, payload)
      }
    })

    this.commit = (mutationName, payload) => {
      this.mutations[mutationName](payload)
    }

    let actions = options.actions
    this.actions = {}
    forEach(actions, (actionName, fn) => {
      this.actions[actionName] = (payload) => {
        fn(this, payload)
      }
    })
    this.dispatch = (actionName, payload) => {
      this.actions[actionName](payload)
    }
  }

  get state() {
    return this.s.state
  }
}

export default {
  install,
  Store
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章