Skip to content
On this page

简单的一个VueStore

js
// this.$store.dispatch
// this.$store.commit('fn', '')
// this.$store.state
// const num = {
//   state: {},
//   mutations: {
//     add: (state, num) => {
//       state.num = num
//     }
//   },
//   actions: {
//     add({ commit, state }, a) {}
//   }
// }

// new Vuex.Store({
//   state: {}
// })

let Vue

class Store {
  constructor (options) {
    this.state = new Vue({
      data: options.state
    })
    this.mutations = options.mutations || {}
    this.actions = options.actions || {}
  }

  commit = (type, arg) => {
    this.mutations[type](this.state, arg)
  }

  dispatch = (type, arg) => {
    this.actions[type]({
      commit: this.commit,
      state: this.state
    }, arg)
  }
}

function install (_Vue) {
  Vue = _Vue
  // 执行install时混入mixin
  Vue.mixin({
    beforeCreate () {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store
      }
    }
  })
}

export default { Store, install }