# 简单的一个VueStore


// 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 }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
更新于: 12/30/2019, 11:59:39 AM