随笔 - 175  文章 - 6  评论 - 0  阅读 - 36429

⑥ 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);
}
posted on   pleaseAnswer  阅读(187)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示