资讯专栏INFORMATION COLUMN

深入学习Vuex

funnyZhang / 2707人阅读

摘要:深入学习作为配合使用的数据状态管理库,针对解决兄弟组件或多层级组件共享数据状态的痛点问题来说,非常好用。至此,构造函数部分已经过了一遍了。

深入学习Vuex

vuex作为配合vue使用的数据状态管理库,针对解决兄弟组件或多层级组件共享数据状态的痛点问题来说,非常好用。本文以使用者的角度,结合源码来学习vuex。其中也参考了许多前辈的文章,参见最后的Reference

Vue加载Vuex(Vue.use(Vuex))

Vue加载Vuex还是很简单的,让我们以官方文档上实例为切入点来开始认识Vuex

</>复制代码

  1. import Vue from "vue"
  2. import Vuex from "vuex"
  3. import cart from "./modules/cart"
  4. import products from "./modules/products"
  5. import createLogger from "../../../src/plugins/logger"
  6. Vue.use(Vuex)
  7. const debug = process.env.NODE_ENV !== "production"
  8. export default new Vuex.Store({
  9. modules: {
  10. cart,
  11. products
  12. },
  13. strict: debug,
  14. plugins: debug ? [createLogger()] : []
  15. })

这段代码我们再熟悉不过了,就是Vue加载Vuex插件,然后new了一个Vuex实例。
我们一步一步来看,首先看一下Vue如何加载的Vuex,也就是Vue.use(Vuex)发生了什么。

</>复制代码

  1. Vue.use = function (plugin: Function | Object) {
  2. /* istanbul ignore if */
  3. /*标识位检测该插件是否已经被安装*/
  4. if (plugin.installed) {
  5. return
  6. }
  7. // additional parameters
  8. const args = toArray(arguments, 1)
  9. /*将this(Vue构造函数)加入数组头部*/
  10. args.unshift(this)
  11. if (typeof plugin.install === "function") {
  12. /*install执行插件安装*/
  13. plugin.install.apply(plugin, args)
  14. } else if (typeof plugin === "function") {
  15. plugin.apply(null, args)
  16. }
  17. //标记插件已安装
  18. plugin.installed = true
  19. return this
  20. }

主要做了几件事:

验证是否已安装,避免重复

如果插件提供install方法,则执行否则把插件当作function执行

最后标记插件已安装

那么Vuex提供install方法了吗?答案是肯定的

</>复制代码

  1. let Vue // bind on install
  2. export function install (_Vue) {
  3. if (Vue) {
  4. /*避免重复安装(Vue.use内部也会检测一次是否重复安装同一个插件)*/
  5. if (process.env.NODE_ENV !== "production") {
  6. console.error(
  7. "[vuex] already installed. Vue.use(Vuex) should be called only once."
  8. )
  9. }
  10. return
  11. }
  12. /*保存Vue,同时用于检测是否重复安装*/
  13. Vue = _Vue//Vue构造函数
  14. /*将vuexInit混淆进Vue的beforeCreate(Vue2.0)或_init方法(Vue1.0)*/
  15. applyMixin(Vue)
  16. }

看mixin之前我们可以先思考一个问题,我们在访问Vuex的数据的时候基本都是这样访问的,比如this.user = this.$store.state.global.user,this.$store是什么时候加到Vue实例上的?applyMixin会给出答案,让我们继续看applyMixin发生了什么

</>复制代码

  1. // applyMixin:
  2. export default function (Vue) {
  3. /*获取Vue版本,鉴别Vue1.0还是Vue2.0*/
  4. const version = Number(Vue.version.split(".")[0])
  5. if (version >= 2) {
  6. /*通过mixin将vuexInit混淆到Vue实例的beforeCreate钩子中*/
  7. Vue.mixin({ beforeCreate: vuexInit })
  8. } else {
  9. // override init and inject vuex init procedure
  10. // for 1.x backwards compatibility.
  11. /*将vuexInit放入_init中调用*/
  12. const _init = Vue.prototype._init
  13. Vue.prototype._init = function (options = {}) {
  14. options.init = options.init
  15. ? [vuexInit].concat(options.init)
  16. : vuexInit
  17. _init.call(this, options)
  18. }
  19. }
  20. /**
  21. * Vuex init hook, injected into each instances init hooks list.
  22. */
  23. /*Vuex的init钩子,会存入每一个Vue实例等钩子列表*/
  24. function vuexInit () {
  25. // this = vue object
  26. const options = this.$options
  27. // store injection
  28. if (options.store) {
  29. /*存在store其实代表的就是Root节点,直接执行store(function时)或者使用store(非function)*/
  30. this.$store = typeof options.store === "function"
  31. ? options.store()
  32. : options.store
  33. } else if (options.parent && options.parent.$store) {
  34. /*子组件直接从父组件中获取$store,这样就保证了所有组件都公用了全局的同一份store*/
  35. this.$store = options.parent.$store
  36. }
  37. }
  38. }

我们这里就只看2.0了,思路就是通过Vue.mixin把挂载$store的动作放在beforeCreate钩子上,由此实现了每个组件实例都可以通过this.$store来直接访问数据。
注意:mixin的细节

同名钩子函数将混合为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。

使用全局混入对象,将会影响到 所有 之后创建的 Vue 实例。

至此,Vue.use(Vuex)我们已经了解完了。

Vuex结构总览

顺着我们实例代码的思路,接下来我们应该开始看构造器了,不过开始看之前,我们先看一下Vuex.store Class都定义了些什么。

</>复制代码

  1. export class Store {
  2. constructor (options = {}) {
  3. }
  4. // state 取值函数(getter)
  5. get state () {
  6. }
  7. //存值函数(setter)
  8. set state (v) {
  9. }
  10. /* 调用mutation的commit方法 */
  11. commit (_type, _payload, _options) {
  12. }
  13. /* 调用action的dispatch方法 */
  14. dispatch (_type, _payload) {
  15. }
  16. /* 注册一个订阅函数,返回取消订阅的函数 */
  17. subscribe (fn) {
  18. }
  19. /* 观察一个getter方法 */
  20. watch (getter, cb, options) {
  21. }
  22. /* 重置state */
  23. replaceState (state) {
  24. }
  25. /* 注册一个动态module,当业务进行异步加载的时候,可以通过该接口进行注册动态module */
  26. registerModule (path, rawModule) {
  27. }
  28. /* 注销一个动态module */
  29. unregisterModule (path) {
  30. }
  31. /* 热更新 */
  32. hotUpdate (newOptions) {
  33. }
  34. /* 保证通过mutation修改store的数据 */
  35. // 内部使用,比如当外部强行改变state的数据时直接报错
  36. _withCommit (fn) {
  37. }
  38. }

以上就是定义的接口了,官方文档上实例属性和方法都在这里找得到。
来看一张大神画的图有助于理解思路

出处见最后。
接下来我们继续实例思路

</>复制代码

  1. export default new Vuex.Store({
  2. modules: {
  3. cart,
  4. products
  5. },
  6. strict: debug,
  7. plugins: debug ? [createLogger()] : []
  8. })

来看一下构造函数

</>复制代码

  1. constructor (options = {}) {
  2. // Auto install if it is not done yet and `window` has `Vue`.
  3. // To allow users to avoid auto-installation in some cases,
  4. // this code should be placed here. See #731
  5. /*
  6. 在浏览器环境下,如果插件还未安装(!Vue即判断是否未安装),则它会自动安装。
  7. 它允许用户在某些情况下避免自动安装。
  8. */
  9. if (!Vue && typeof window !== "undefined" && window.Vue) {
  10. install(window.Vue) // 将store注册到实例或conponent
  11. }
  12. if (process.env.NODE_ENV !== "production") {
  13. assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`)
  14. assert(typeof Promise !== "undefined", `vuex requires a Promise polyfill in this browser.`)
  15. //检查是不是new 操作符调用的
  16. assert(this instanceof Store, `Store must be called with the new operator.`)
  17. }
  18. const {
  19. /*一个数组,包含应用在 store 上的插件方法。这些插件直接接收 store 作为唯一参数,可以监听 mutation(用于外部地数据持久化、记录或调试)或者提交 mutation (用于内部数据,例如 websocket 或 某些观察者)*/
  20. plugins = [],
  21. /*使 Vuex store 进入严格模式,在严格模式下,任何 mutation 处理函数以外修改 Vuex state 都会抛出错误。*/
  22. strict = false
  23. } = options
  24. /*从option中取出state,如果state是function则执行,最终得到一个对象*/
  25. let {
  26. state = {}
  27. } = options
  28. if (typeof state === "function") {
  29. state = state()
  30. }
  31. // store internal state
  32. /* 用来判断严格模式下是否是用mutation修改state的 */
  33. this._committing = false
  34. /* 存放action */
  35. this._actions = Object.create(null)
  36. /* 存放mutation */
  37. this._mutations = Object.create(null)
  38. /* 存放getter */
  39. //包装后的getter
  40. this._wrappedGetters = Object.create(null)
  41. /* module收集器 */
  42. this._modules = new ModuleCollection(options)
  43. /* 根据namespace存放module */
  44. this._modulesNamespaceMap = Object.create(null)
  45. /* 存放订阅者 外部插件使用 */
  46. this._subscribers = []
  47. /* 用以实现Watch的Vue实例 */
  48. this._watcherVM = new Vue()
  49. // bind commit and dispatch to self
  50. /*将dispatch与commit调用的this绑定为store对象本身,否则在组件内部this.dispatch时的this会指向组件的vm*/
  51. const store = this
  52. const {dispatch, commit} = this
  53. /* 为dispatch与commit绑定this(Store实例本身) */
  54. this.dispatch = function boundDispatch (type, payload) {
  55. return dispatch.call(store, type, payload)
  56. }
  57. this.commit = function boundCommit (type, payload, options) {
  58. return commit.call(store, type, payload, options)
  59. }
  60. // strict mode
  61. /*严格模式(使 Vuex store 进入严格模式,在严格模式下,任何 mutation 处理函数以外修改 Vuex state 都会抛出错误)*/
  62. this.strict = strict
  63. // init root module.
  64. // this also recursively registers all sub-modules
  65. // and collects all module getters inside this._wrappedGetters
  66. /*初始化根module,这也同时递归注册了所有子modle,收集所有modulegetter_wrappedGetters中去,this._modules.root代表根module才独有保存的Module对象*/
  67. installModule(this, state, [], this._modules.root)
  68. // initialize the store vm, which is responsible for the reactivity
  69. // (also registers _wrappedGetters as computed properties)
  70. /* 通过vm重设store,新建Vue对象使用Vue内部的响应式实现注册state以及computed */
  71. resetStoreVM(this, state)
  72. // apply plugins
  73. /* 调用插件 */
  74. plugins.forEach(plugin => plugin(this))
  75. /* devtool插件 */
  76. if (Vue.config.devtools) {
  77. devtoolPlugin(this)
  78. }
  79. }

Vuex的源码一共就一千行左右,构造函数吃透基本掌握至少一半了,构造函数中主要是初始化各种属性。简单的详见注释,这里我们主要看如何解析处理modules,首先来看this._modules = new ModuleCollection(options),ModuleCollection结构如下

</>复制代码

  1. import Module from "./module"
  2. import { assert, forEachValue } from "../util"
  3. /*module收集类*/
  4. export default class ModuleCollection {
  5. constructor (rawRootModule) { // new store(options)
  6. // register root module (Vuex.Store options)
  7. this.register([], rawRootModule, false)
  8. }
  9. /*获取父级module*/
  10. get (path) {
  11. }
  12. /*
  13. 获取namespace,当namespaced为true的时候会返回"moduleName/name"
  14. 默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
  15. 如果希望你的模块更加自包含或提高可重用性,你可以通过添加 namespaced: true 的方式使其成为命名空间模块。
  16. 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
  17. */
  18. getNamespace (path) {
  19. }
  20. update (rawRootModule) {
  21. }
  22. /*注册*/
  23. register (path, rawModule, runtime = true) {
  24. if (process.env.NODE_ENV !== "production") {
  25. assertRawModule(path, rawModule)
  26. }
  27. /*新建一个Module对象*/
  28. const newModule = new Module(rawModule, runtime)
  29. if (path.length === 0) {
  30. /*path为空数组的代表跟节点*/
  31. this.root = newModule
  32. } else {
  33. /*获取父级module*/
  34. const parent = this.get(path.slice(0, -1))//排除倒数第一个元素的数组,
  35. /*在父module中插入一个子module*/
  36. parent.addChild(path[path.length - 1], newModule)
  37. }
  38. // register nested modules
  39. /*递归注册module*/
  40. if (rawModule.modules) {
  41. forEachValue(rawModule.modules, (rawChildModule, key) => {
  42. // concat不改变源数组,返回合并后的数组
  43. this.register(path.concat(key), rawChildModule, runtime)
  44. })
  45. }
  46. }
  47. /*注销*/
  48. unregister (path) {
  49. }
  50. }
  51. /*Module构造类*/
  52. export default class Module {
  53. constructor (rawModule, runtime) {
  54. this.runtime = runtime
  55. this._children = Object.create(null)
  56. /*保存module*/
  57. this._rawModule = rawModule
  58. /*保存modele的state*/
  59. const rawState = rawModule.state
  60. this.state = (typeof rawState === "function" ? rawState() : rawState) || {}
  61. }
  62. /* 获取namespace */
  63. get namespaced () {
  64. }
  65. /*插入一个子module,存入_children中*/
  66. addChild (key, module) {
  67. this._children[key] = module
  68. }
  69. /*移除一个子module*/
  70. removeChild (key) {
  71. }
  72. /*根据key获取子module*/
  73. getChild (key) {
  74. return this._children[key]
  75. }
  76. /* 更新module */
  77. update (rawModule) {
  78. }
  79. /* 遍历child */
  80. forEachChild (fn) {
  81. }
  82. /* 遍历getter */
  83. forEachGetter (fn) {
  84. }
  85. /* 遍历action */
  86. forEachAction (fn) {
  87. }
  88. /* 遍历matation */
  89. forEachMutation (fn) {
  90. }
  91. }

ModuleCollection的作用就是收集和管理Module,构造函数中对我们传入的options的module进行了注册(register 是重点,详见注释,注册方法中使用了递归,以此来注册所有的module)。我们给出的实例经过ModuleCollection的收集之后变成了什么样子呢?

</>复制代码

  1. //this._modules简单结构示例
  2. {
  3. root: {
  4. state: {},
  5. _children: {
  6. cart: {
  7. ...
  8. },
  9. products: {
  10. ...
  11. }
  12. }
  13. }
  14. }

收集完了之后,我们看一下是如何初始化这些module的installModule(this, state, [], this._modules.root)

</>复制代码

  1. function installModule (store, rootState, path, module, hot) {
  2. /* 是否是根module */
  3. const isRoot = !path.length
  4. /* 获取modulenamespace */
  5. const namespace = store._modules.getNamespace(path)
  6. // register in namespace map
  7. /* 如果有namespace则在_modulesNamespaceMap中注册 */
  8. if (module.namespaced) {
  9. store._modulesNamespaceMap[namespace] = module
  10. }
  11. // set state
  12. if (!isRoot && !hot) {
  13. /* 获取父级的state */
  14. const parentState = getNestedState(rootState, path.slice(0, -1))//深度取值,并返回取到的值
  15. /* modulename */
  16. const moduleName = path[path.length - 1]
  17. store._withCommit(() => {// 添加响应式属性
  18. /* 将子module设置称响应式的 */
  19. Vue.set(parentState, moduleName, module.state)
  20. })
  21. }
  22. // 当前模块上下文信息
  23. const local = module.context = makeLocalContext(store, namespace, path)
  24. /* 遍历注册mutation */
  25. //mutation:key对应的handler
  26. module.forEachMutation((mutation, key) => {
  27. const namespacedType = namespace + key
  28. registerMutation(store, namespacedType, mutation, local)
  29. })
  30. /* 遍历注册action */
  31. module.forEachAction((action, key) => {
  32. const namespacedType = namespace + key
  33. registerAction(store, namespacedType, action, local)
  34. })
  35. /* 遍历注册getter */
  36. module.forEachGetter((getter, key) => {
  37. const namespacedType = namespace + key
  38. registerGetter(store, namespacedType, getter, local)
  39. })
  40. /* 递归安装mudule */
  41. module.forEachChild((child, key) => {
  42. installModule(store, rootState, path.concat(key), child, hot)
  43. })
  44. }

在这里构造了各个module的信息也就是localConext,包括各个模块的mutation,action ,getter ,mudule ,其中运用到了许多包装的技巧(主要为了计算模块的路径),还有代理的方式访问数据,详见注释

resetStoreVM方法思路就是借助Vue响应式来实现Vuex的响应式

</>复制代码

  1. /* 通过vm重设store,新建Vue对象使用Vue内部的响应式实现注册state以及computed */
  2. function resetStoreVM (store, state, hot) {
  3. /* 存放之前的vm对象 */
  4. const oldVm = store._vm
  5. // bind store public getters
  6. store.getters = {}
  7. const wrappedGetters = store._wrappedGetters
  8. const computed = {}
  9. /* 通过Object.defineProperty为每一个getter方法设置get方法,比如获取this.$store.getters.test的时候获取的是store._vm.test,也就是Vue对象的computed属性 */
  10. // key = wrappedGetters的key,fn = wrappedGetters的key对应的value
  11. forEachValue(wrappedGetters, (fn, key) => {
  12. // use computed to leverage its lazy-caching mechanism
  13. computed[key] = () => fn(store)
  14. // store.getter并没有像state一样在class直接注册了gettersetter,而是在这里定义的
  15. // 用过代理的方式借助Vue计算属性实现了Vuex的计算属性
  16. Object.defineProperty(store.getters, key, {
  17. get: () => store._vm[key], // 获取计算苏属性(响应式)
  18. enumerable: true // for local getters
  19. })
  20. })
  21. // use a Vue instance to store the state tree
  22. // suppress warnings just in case the user has added
  23. // some funky global mixins
  24. const silent = Vue.config.silent
  25. /* Vue.config.silent暂时设置为true的目的是在new一个Vue实例的过程中不会报出一切警告 */
  26. Vue.config.silent = true
  27. /* 这里new了一个Vue对象,运用Vue内部的响应式实现注册state以及computed*/
  28. //通过Vue的数据劫持,创造了dep,在Vue实例中使用的话Watcher会收集依赖,以达到响应式的目的
  29. store._vm = new Vue({
  30. data: {
  31. $$state: state
  32. },
  33. computed
  34. })
  35. Vue.config.silent = silent
  36. // enable strict mode for new vm
  37. /* 使能严格模式,保证修改store只能通过mutation */
  38. if (store.strict) {
  39. enableStrictMode(store)
  40. }
  41. if (oldVm) {
  42. /* 解除旧vm的state的引用,以及销毁旧的Vue对象 */
  43. if (hot) {
  44. // dispatch changes in all subscribed watchers
  45. // to force getter re-evaluation for hot reloading.
  46. store._withCommit(() => {
  47. oldVm._data.$$state = null
  48. })
  49. }
  50. Vue.nextTick(() => oldVm.$destroy())
  51. }
  52. }

在这里只要是把Vuex也构造为响应式的,store._vm指向一个Vue的实例,借助Vue数据劫持,创造了dep,在组件实例中使用的话Watcher会收集依赖,以达到响应式的目的。
至此,构造函数部分已经过了一遍了。

最后

本文主要是学习了Vuex的初始化部分,实际的Vuex的api接口的实现也有相关的中文注释,我已经把主要部分中文注释代码放在这里,需者自取中文注释代码
学习过程中参考了许多大神的文章,一并感谢。

Reference

Vue.js 源码解析(参考了大神的许多注释,大神写的太详尽了,我只补充了一部分)
Vuex框架原理与源码分析

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/52589.html

相关文章

  • 一张思维导图辅助你深入了解 Vue | Vue-Router | Vuex 源码架构

    摘要:前言本文内容讲解的内容一张思维导图辅助你深入了解源码架构。总结以上内容是笔者最近学习源码时的收获与所做的笔记,本文内容大多是开源项目技术揭秘的内容,只不过是以思维导图的形式来展现,内容有省略,还加入了笔者的一点理解。1.前言 本文内容讲解的内容:一张思维导图辅助你深入了解 Vue | Vue-Router | Vuex 源码架构。 项目地址:github.com/biaochenxuy… 文...

    weij 评论0 收藏0
  • 深入学习Vuex

    摘要:深入学习作为配合使用的数据状态管理库,针对解决兄弟组件或多层级组件共享数据状态的痛点问题来说,非常好用。至此,构造函数部分已经过了一遍了。 深入学习Vuex vuex作为配合vue使用的数据状态管理库,针对解决兄弟组件或多层级组件共享数据状态的痛点问题来说,非常好用。本文以使用者的角度,结合源码来学习vuex。其中也参考了许多前辈的文章,参见最后的Reference Vue加载Vuex...

    codercao 评论0 收藏0
  • 深入理解js

    摘要:详解十大常用设计模式力荐深度好文深入理解大设计模式收集各种疑难杂症的问题集锦关于,工作和学习过程中遇到过许多问题,也解答过许多别人的问题。介绍了的内存管理。 延迟加载 (Lazyload) 三种实现方式 延迟加载也称为惰性加载,即在长网页中延迟加载图像。用户滚动到它们之前,视口外的图像不会加载。本文详细介绍了三种延迟加载的实现方式。 详解 Javascript十大常用设计模式 力荐~ ...

    caikeal 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<