什么是vuex

  • vuex是专门为vue.js设计的状态管理库
  • vuex采用集中式的方式存储需要共享的状态
  • vuex的作用是进行状态管理,解决复杂组件通信、数据共享
  • vuex集成到了devtools中,提供了time-travel时光旅行历史回滚功能

使用Vue.use()模拟vuex

let _Vue = null
class Store {
  constructor(options) {
    const { state = {}, getters = {}, mutations = {}, actions = {} } = options
    this.state = _Vue.observable(state)
    this.getters = Object.create(null)
    Object.keys(getters).forEach((key) => {
      Object.defineProperty(this.getters, key, {
        get: () => getters[key](state),
      })
    })

    this._mutations = mutations
    this._actions = actions
  }

  commit(type, payload) {
    this._mutations[type](this.state, payload)
  }
  dispatch(type, payload) {
    this._actions[type](this, payload)
  }
}

function install(Vue) {
  _Vue = Vue
  _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
Last Updated: