⑥ Vuex状态管理的工作原理

1 为什么要使用 Vuex

解决多组件通讯问题

  • Vuex 是一个专门为 Vue.js 框架设计的状态管理工具

  • Vuex 借鉴了 flux、redux 的基本思想,将状态抽离到全局,形成一个 Store

  • Vuex 内部采用了 new Vue 来将 Store 内的数据进行 响应式化

2 安装

2.1 Vue 提供了一个 Vue.use() 来安装插件,内部会调用插件提供的 install 方法

Vue.use(Vuex);

2.2 Vuex 提供一个 install 方法来安装:采用 Vue.mixin 方法将 vuexInit 方法混进 beforeCreate 钩子中,并用 Vue 保存 Vue 对象

let Vue;
export default install(_Vue) {
    Vue.mixin({ beforeCreate: vuexInit });
    Vue = _Vue;
}

2.3 vuexInit 方法实现了什么?

在使用 Vuex 时,需要将 store 传入到 Vue 实例中

  1. vuexInit 方法实现了在每一个 vm 中都可以访问该 store

  2. 如果是根节点($options 中存在 store 说明是根节点),则直接将 options.store 赋值给 this.$store

  3. 否则说明不是根节点,从父节点的 $store 中获取

function vuexInit() {
    const options = this.$options;
    if(options.store) {
        this.$store = options.store;
    } else {
        this.$store = options.parent.$store;
    }
}

3 Store

3.1 数据的响应式化

Store 构造函数中对 state 进行响应式化
  • state 会将需要的依赖收集在 Dep 中,在被修改时更新对应视图
constructor() {
    this._vm = new Vue({
        data: {
            ?state: this.state
        }
    })
}

3.2 commit

commit 方法用来触发 mutation
  • _mutations 中取出对应的 mutation,循环执行其中的每一个 mutation
commit(type, payload, _options) {
    const entry = this._mutations[type];
    entry.forEach(funciton commitIterator(handler) {
        handler(payload);
    })
}

3.3 dispatch

dispatch 用于触发 action,可以包含异步状态
  • 取出 _actions 中的所有对应 action,将其执行,如果有多个则用 Promise.all 进行包装
dispatch(type, payload) {
    const entry = this._actions[type];
    return entry.length > 1 
    ? Promise.all(entry.map(handler => handler(payload)))
    : entry[0](payload);
}
原文地址:https://www.cnblogs.com/pleaseAnswer/p/14331333.html