资讯专栏INFORMATION COLUMN

Vuex源码阅读分析

Eastboat / 2284人阅读

摘要:源码阅读分析是专为开发的统一状态管理工具。本文将会分析的整个实现思路,当是自己读完源码的一个总结。再次回到构造函数,接下来是各类插件的注册插件注册到这里的初始化工作已经完成。

Vuex源码阅读分析

Vuex是专为Vue开发的统一状态管理工具。当我们的项目不是很复杂时,一些交互可以通过全局事件总线解决,但是这种观察者模式有些弊端,开发时可能没什么感觉,但是当项目变得复杂,维护时往往会摸不着头脑,如果是后来加入的伙伴更会觉得很无奈。这时候可以采用Vuex方案,它可以使得我们的项目的数据流变得更加清晰。本文将会分析Vuex的整个实现思路,当是自己读完源码的一个总结。

目录结构

module:提供对module的处理,主要是对state的处理,最后构建成一棵module tree

plugins:和devtools配合的插件,提供像时空旅行这样的调试功能。

helpers:提供如mapActions、mapMutations这样的api

index、index.esm:源码的主入口,抛出Store和mapActions等api,一个用于commonjs的打包、一个用于es module的打包

mixin:提供install方法,用于注入$store

store:vuex的核心代码

util:一些工具函数,如deepClone、isPromise、assert

源码分析

先从一个简单的示例入手,一步一步分析整个代码的执行过程,下面是官方提供的简单示例

</>复制代码

  1. // store.js
  2. import Vue from "vue"
  3. import Vuex from "vuex"
  4. Vue.use(Vuex)
1. Vuex的注册

Vue官方建议的插件使用方法是使用Vue.use方法,这个方法会调用插件的install方法,看看install方法都做了些什么,从index.js中可以看到install方法在store.js中抛出,部分代码如下

</>复制代码

  1. let Vue // bind on install
  2. export function install (_Vue) {
  3. if (Vue && _Vue === Vue) {
  4. if (process.env.NODE_ENV !== "production") {
  5. console.error(
  6. "[vuex] already installed. Vue.use(Vuex) should be called only once."
  7. )
  8. }
  9. return
  10. }
  11. Vue = _Vue
  12. applyMixin(Vue)
  13. }

声明了一个Vue变量,这个变量在install方法中会被赋值,这样可以给当前作用域提供Vue,这样做的好处是不需要额外import Vue from "vue" 不过我们也可以这样写,然后让打包工具不要将其打包,而是指向开发者所提供的Vue,比如webpack的externals,这里就不展开了。执行install会先判断Vue是否已经被赋值,避免二次安装。然后调用applyMixin方法,代码如下

</>复制代码

  1. // applyMixin
  2. export default function (Vue) {
  3. const version = Number(Vue.version.split(".")[0])
  4. if (version >= 2) {
  5. Vue.mixin({ beforeCreate: vuexInit })
  6. } else {
  7. // override init and inject vuex init procedure
  8. // for 1.x backwards compatibility.
  9. const _init = Vue.prototype._init
  10. Vue.prototype._init = function (options = {}) {
  11. options.init = options.init
  12. ? [vuexInit].concat(options.init)
  13. : vuexInit
  14. _init.call(this, options)
  15. }
  16. }
  17. /**
  18. * Vuex init hook, injected into each instances init hooks list.
  19. */
  20. function vuexInit () {
  21. const options = this.$options
  22. // store injection
  23. // 当我们在执行new Vue的时候,需要提供store字段
  24. if (options.store) {
  25. // 如果是root,将store绑到this.$store
  26. this.$store = typeof options.store === "function"
  27. ? options.store()
  28. : options.store
  29. } else if (options.parent && options.parent.$store) {
  30. // 否则拿parent上的$store
  31. // 从而实现所有组件共用一个store实例
  32. this.$store = options.parent.$store
  33. }
  34. }
  35. }

这里会区分vue的版本,2.x和1.x的钩子是不一样的,如果是2.x使用beforeCreate,1.x即使用_init。当我们在执行new Vue启动一个Vue应用程序时,需要给上store字段,根组件从这里拿到store,子组件从父组件拿到,这样一层一层传递下去,实现所有组件都有$store属性,这样我们就可以在任何组件中通过this.$store访问到store

接下去继续看例子

</>复制代码

  1. // store.js
  2. export default new Vuex.Store({
  3. state: {
  4. count: 0
  5. },
  6. getters: {
  7. evenOrOdd: state => state.count % 2 === 0 ? "even" : "odd"
  8. },
  9. actions: {
  10. increment: ({ commit }) => commit("increment"),
  11. decrement: ({ commit }) => commit("decrement")
  12. },
  13. mutations: {
  14. increment (state) {
  15. state.count++
  16. },
  17. decrement (state) {
  18. state.count--
  19. }
  20. }
  21. })

</>复制代码

  1. // app.js
  2. new Vue({
  3. el: "#app",
  4. store, // 传入store,在beforeCreate钩子中会用到
  5. render: h => h(Counter)
  6. })
2.store初始化

这里是调用Store构造函数,传入一个对象,包括state、actions等等,接下去看看Store构造函数都做了些什么

</>复制代码

  1. export class Store {
  2. constructor (options = {}) {
  3. if (!Vue && typeof window !== "undefined" && window.Vue) {
  4. // 挂载在window上的自动安装,也就是通过script标签引入时不需要手动调用Vue.use(Vuex)
  5. install(window.Vue)
  6. }
  7. if (process.env.NODE_ENV !== "production") {
  8. // 断言必须使用Vue.use(Vuex),在install方法中会给Vue赋值
  9. // 断言必须存在Promise
  10. // 断言必须使用new操作符
  11. assert(Vue, `must call Vue.use(Vuex) before creating a store instance.`)
  12. assert(typeof Promise !== "undefined", `vuex requires a Promise polyfill in this browser.`)
  13. assert(this instanceof Store, `Store must be called with the new operator.`)
  14. }
  15. const {
  16. plugins = [],
  17. strict = false
  18. } = options
  19. // store internal state
  20. this._committing = false
  21. this._actions = Object.create(null)
  22. this._actionSubscribers = []
  23. this._mutations = Object.create(null)
  24. this._wrappedGetters = Object.create(null)
  25. // 这里进行module收集,只处理了state
  26. this._modules = new ModuleCollection(options)
  27. // 用于保存namespaced的模块
  28. this._modulesNamespaceMap = Object.create(null)
  29. // 用于监听mutation
  30. this._subscribers = []
  31. // 用于响应式地监测一个 getter 方法的返回值
  32. this._watcherVM = new Vue()
  33. // 将dispatch和commit方法的this指针绑定到store上,防止被修改
  34. const store = this
  35. const { dispatch, commit } = this
  36. this.dispatch = function boundDispatch (type, payload) {
  37. return dispatch.call(store, type, payload)
  38. }
  39. this.commit = function boundCommit (type, payload, options) {
  40. return commit.call(store, type, payload, options)
  41. }
  42. // strict mode
  43. this.strict = strict
  44. const state = this._modules.root.state
  45. // 这里是module处理的核心,包括处理根module、action、mutation、getters和递归注册子module
  46. installModule(this, state, [], this._modules.root)
  47. // 使用vue实例来保存state和getter
  48. resetStoreVM(this, state)
  49. // 插件注册
  50. plugins.forEach(plugin => plugin(this))
  51. if (Vue.config.devtools) {
  52. devtoolPlugin(this)
  53. }
  54. }
  55. }

首先会判断Vue是不是挂载在window上,如果是的话,自动调用install方法,然后进行断言,必须先调用Vue.use(Vuex)。必须提供Promise,这里应该是为了让Vuex的体积更小,让开发者自行提供Promisepolyfill,一般我们可以使用babel-runtime或者babel-polyfill引入。最后断言必须使用new操作符调用Store函数。

接下去是一些内部变量的初始化
_committing提交状态的标志,在_withCommit中,当使用mutation时,会先赋值为true,再执行mutation,修改state后再赋值为false,在这个过程中,会用watch监听state的变化时是否_committing为true,从而保证只能通过mutation来修改state
_actions用于保存所有action,里面会先包装一次
_actionSubscribers用于保存订阅action的回调
_mutations用于保存所有的mutation,里面会先包装一次
_wrappedGetters用于保存包装后的getter
_modules用于保存一棵module树
_modulesNamespaceMap用于保存namespaced的模块

接下去的重点是

</>复制代码

  1. this._modules = new ModuleCollection(options)
2.1 模块收集

接下去看看ModuleCollection函数都做了什么,部分代码如下

</>复制代码

  1. // module-collection.js
  2. export default class ModuleCollection {
  3. constructor (rawRootModule) {
  4. // 注册 root module (Vuex.Store options)
  5. this.register([], rawRootModule, false)
  6. }
  7. get (path) {
  8. // 根据path获取module
  9. return path.reduce((module, key) => {
  10. return module.getChild(key)
  11. }, this.root)
  12. }
  13. /*
  14. * 递归注册module path是路径 如
  15. * {
  16. * modules: {
  17. * a: {
  18. * state: {}
  19. * }
  20. * }
  21. * }
  22. * a模块的path => ["a"]
  23. * 根模块的path => []
  24. */
  25. register (path, rawModule, runtime = true) {
  26. if (process.env.NODE_ENV !== "production") {
  27. // 断言 rawModule中的getters、actions、mutations必须为指定的类型
  28. assertRawModule(path, rawModule)
  29. }
  30. // 实例化一个module
  31. const newModule = new Module(rawModule, runtime)
  32. if (path.length === 0) {
  33. //module 绑定到root属性上
  34. this.root = newModule
  35. } else {
  36. //module 添加其父module的_children属性上
  37. const parent = this.get(path.slice(0, -1))
  38. parent.addChild(path[path.length - 1], newModule)
  39. }
  40. // 如果当前模块存在子模块(modules字段)
  41. // 遍历子模块,逐个注册,最终形成一个树
  42. if (rawModule.modules) {
  43. forEachValue(rawModule.modules, (rawChildModule, key) => {
  44. this.register(path.concat(key), rawChildModule, runtime)
  45. })
  46. }
  47. }
  48. }
  49. // module.js
  50. export default class Module {
  51. constructor (rawModule, runtime) {
  52. // 初始化时runtime为false
  53. this.runtime = runtime
  54. // Store some children item
  55. // 用于保存子模块
  56. this._children = Object.create(null)
  57. // Store the origin module object which passed by programmer
  58. // 保存原来的moudle,在Store的installModule中会处理actions、mutations等
  59. this._rawModule = rawModule
  60. const rawState = rawModule.state
  61. // Store the origin module"s state
  62. // 保存state
  63. this.state = (typeof rawState === "function" ? rawState() : rawState) || {}
  64. }
  65. addChild (key, module) {
  66. // 将子模块添加到_children中
  67. this._children[key] = module
  68. }
  69. }

这里调用ModuleCollection构造函数,通过path的长度判断是否为根module,首先进行根module的注册,然后递归遍历所有的module,子module 添加其父module的_children属性上,最终形成一棵树

接着,还是一些变量的初始化,然后

2.2 绑定commit和dispatch的this指针

</>复制代码

  1. // 绑定commit和dispatch的this指针
  2. const store = this
  3. const { dispatch, commit } = this
  4. this.dispatch = function boundDispatch (type, payload) {
  5. return dispatch.call(store, type, payload)
  6. }
  7. this.commit = function boundCommit (type, payload, options) {
  8. return commit.call(store, type, payload, options)
  9. }

这里会将dispath和commit方法的this指针绑定为store,比如下面这样的骚操作,也不会影响到程序的运行

</>复制代码

  1. this.$store.dispatch.call(this, "someAction", payload)
2.3 模块安装

接着是store的核心代码

</>复制代码

  1. // 这里是module处理的核心,包括处理根module、命名空间、action、mutation、getters和递归注册子module
  2. installModule(this, state, [], this._modules.root)

</>复制代码

  1. function installModule (store, rootState, path, module, hot) {
  2. const isRoot = !path.length
  3. /*
  4. * {
  5. * // ...
  6. * modules: {
  7. * moduleA: {
  8. * namespaced: true
  9. * },
  10. * moduleB: {}
  11. * }
  12. * }
  13. * moduleA的namespace -> "moduleA/"
  14. * moduleB的namespace -> ""
  15. */
  16. const namespace = store._modules.getNamespace(path)
  17. // register in namespace map
  18. if (module.namespaced) {
  19. // 保存namespaced模块
  20. store._modulesNamespaceMap[namespace] = module
  21. }
  22. // set state
  23. if (!isRoot && !hot) {
  24. // 非根组件设置state
  25. // 根据path获取父state
  26. const parentState = getNestedState(rootState, path.slice(0, -1))
  27. // 当前的module
  28. const moduleName = path[path.length - 1]
  29. store._withCommit(() => {
  30. // 使用Vue.set将state设置为响应式
  31. Vue.set(parentState, moduleName, module.state)
  32. })
  33. console.log("end", store)
  34. }
  35. // 设置module的上下文,从而保证mutation和action的第一个参数能拿到对应的state getter等
  36. const local = module.context = makeLocalContext(store, namespace, path)
  37. // 逐一注册mutation
  38. module.forEachMutation((mutation, key) => {
  39. const namespacedType = namespace + key
  40. registerMutation(store, namespacedType, mutation, local)
  41. })
  42. // 逐一注册action
  43. module.forEachAction((action, key) => {
  44. const type = action.root ? key : namespace + key
  45. const handler = action.handler || action
  46. registerAction(store, type, handler, local)
  47. })
  48. // 逐一注册getter
  49. module.forEachGetter((getter, key) => {
  50. const namespacedType = namespace + key
  51. registerGetter(store, namespacedType, getter, local)
  52. })
  53. // 逐一注册子module
  54. module.forEachChild((child, key) => {
  55. installModule(store, rootState, path.concat(key), child, hot)
  56. })
  57. }

首先保存namespaced模块到store._modulesNamespaceMap,再判断是否为根组件且不是hot,得到父级module的state和当前module的name,调用Vue.set(parentState, moduleName, module.state)将当前module的state挂载到父state上。接下去会设置module的上下文,因为可能存在namespaced,需要额外处理

</>复制代码

  1. // 设置module的上下文,绑定对应的dispatch、commit、getters、state
  2. function makeLocalContext (store, namespace, path) {
  3. // namespace 如"moduleA/"
  4. const noNamespace = namespace === ""
  5. const local = {
  6. // 如果没有namespace,直接使用原来的
  7. dispatch: noNamespace ? store.dispatch : (_type, _payload, _options) => {
  8. // 统一格式 因为支持payload风格和对象风格
  9. const args = unifyObjectStyle(_type, _payload, _options)
  10. const { payload, options } = args
  11. let { type } = args
  12. // 如果root: true 不会加上namespace 即在命名空间模块里提交根的 action
  13. if (!options || !options.root) {
  14. // 加上命名空间
  15. type = namespace + type
  16. if (process.env.NODE_ENV !== "production" && !store._actions[type]) {
  17. console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`)
  18. return
  19. }
  20. }
  21. // 触发action
  22. return store.dispatch(type, payload)
  23. },
  24. commit: noNamespace ? store.commit : (_type, _payload, _options) => {
  25. // 统一格式 因为支持payload风格和对象风格
  26. const args = unifyObjectStyle(_type, _payload, _options)
  27. const { payload, options } = args
  28. let { type } = args
  29. // 如果root: true 不会加上namespace 即在命名空间模块里提交根的 mutation
  30. if (!options || !options.root) {
  31. // 加上命名空间
  32. type = namespace + type
  33. if (process.env.NODE_ENV !== "production" && !store._mutations[type]) {
  34. console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`)
  35. return
  36. }
  37. }
  38. // 触发mutation
  39. store.commit(type, payload, options)
  40. }
  41. }
  42. // getters and state object must be gotten lazily
  43. // because they will be changed by vm update
  44. // 这里的getters和state需要延迟处理,需要等数据更新后才进行计算,所以使用getter函数,当访问的时候再进行一次计算
  45. Object.defineProperties(local, {
  46. getters: {
  47. get: noNamespace
  48. ? () => store.getters
  49. : () => makeLocalGetters(store, namespace) // 获取namespace下的getters
  50. },
  51. state: {
  52. get: () => getNestedState(store.state, path)
  53. }
  54. })
  55. return local
  56. }
  57. function makeLocalGetters (store, namespace) {
  58. const gettersProxy = {}
  59. const splitPos = namespace.length
  60. Object.keys(store.getters).forEach(type => {
  61. // 如果getter不在该命名空间下 直接return
  62. if (type.slice(0, splitPos) !== namespace) return
  63. // 去掉type上的命名空间
  64. const localType = type.slice(splitPos)
  65. // Add a port to the getters proxy.
  66. // Define as getter property because
  67. // we do not want to evaluate the getters in this time.
  68. // 给getters加一层代理 这样在module中获取到的getters不会带命名空间,实际返回的是store.getters[type] type是有命名空间的
  69. Object.defineProperty(gettersProxy, localType, {
  70. get: () => store.getters[type],
  71. enumerable: true
  72. })
  73. })
  74. return gettersProxy
  75. }

这里会判断modulenamespace是否存在,不存在不会对dispatchcommit做处理,如果存在,给type加上namespace,如果声明了{root: true}也不做处理,另外gettersstate需要延迟处理,需要等数据更新后才进行计算,所以使用Object.defineProperties的getter函数,当访问的时候再进行计算

再回到上面的流程,接下去是逐步注册mutation action getter 子module,先看注册mutation

</>复制代码

  1. /*
  2. * 参数是store、mutation的key(namespace处理后的)、handler函数、当前module上下文
  3. */
  4. function registerMutation (store, type, handler, local) {
  5. // 首先判断store._mutations是否存在,否则给空数组
  6. const entry = store._mutations[type] || (store._mutations[type] = [])
  7. // 将mutation包一层函数,push到数组中
  8. entry.push(function wrappedMutationHandler (payload) {
  9. // 包一层,commit执行时只需要传入payload
  10. // 执行时让this指向store,参数为当前module上下文的state和用户额外添加的payload
  11. handler.call(store, local.state, payload)
  12. })
  13. }

mutation的注册比较简单,主要是包一层函数,然后保存到store._mutations里面,在这里也可以知道,mutation可以重复注册,不会覆盖,当用户调用this.$store.commit(mutationType, payload)时会触发,接下去看看commit函数

</>复制代码

  1. // 这里的this已经被绑定为store
  2. commit (_type, _payload, _options) {
  3. // 统一格式,因为支持对象风格和payload风格
  4. const {
  5. type,
  6. payload,
  7. options
  8. } = unifyObjectStyle(_type, _payload, _options)
  9. const mutation = { type, payload }
  10. // 获取当前type对应保存下来的mutations数组
  11. const entry = this._mutations[type]
  12. if (!entry) {
  13. // 提示不存在该mutation
  14. if (process.env.NODE_ENV !== "production") {
  15. console.error(`[vuex] unknown mutation type: ${type}`)
  16. }
  17. return
  18. }
  19. // 包裹在_withCommit中执行mutation,mutation是修改state的唯一方法
  20. this._withCommit(() => {
  21. entry.forEach(function commitIterator (handler) {
  22. // 执行mutation,只需要传入payload,在上面的包裹函数中已经处理了其他参数
  23. handler(payload)
  24. })
  25. })
  26. // 执行mutation的订阅者
  27. this._subscribers.forEach(sub => sub(mutation, this.state))
  28. if (
  29. process.env.NODE_ENV !== "production" &&
  30. options && options.silent
  31. ) {
  32. // 提示silent参数已经移除
  33. console.warn(
  34. `[vuex] mutation type: ${type}. Silent option has been removed. ` +
  35. "Use the filter functionality in the vue-devtools"
  36. )
  37. }
  38. }

首先对参数进行统一处理,因为是支持对象风格和载荷风格的,然后拿到当前type对应的mutation数组,使用_withCommit包裹逐一执行,这样我们执行this.$store.commit的时候会调用对应的mutation,而且第一个参数是state,然后再执行mutation的订阅函数

接下去看action的注册

</>复制代码

  1. /*
  2. * 参数是store、type(namespace处理后的)、handler函数、module上下文
  3. */
  4. function registerAction (store, type, handler, local) {
  5. // 获取_actions数组,不存在即赋值为空数组
  6. const entry = store._actions[type] || (store._actions[type] = [])
  7. // push到数组中
  8. entry.push(function wrappedActionHandler (payload, cb) {
  9. // 包一层,执行时需要传入payload和cb
  10. // 执行action
  11. let res = handler.call(
  12. store,
  13. {
  14. dispatch: local.dispatch,
  15. commit: local.commit,
  16. getters: local.getters,
  17. state: local.state,
  18. rootGetters: store.getters,
  19. rootState: store.state
  20. },
  21. payload,
  22. cb
  23. )
  24. // 如果action的执行结果不是promise,将他包裹为promise,这样就支持promise的链式调用
  25. if (!isPromise(res)) {
  26. res = Promise.resolve(res)
  27. }
  28. if (store._devtoolHook) {
  29. // 使用devtool处理一次error
  30. return res.catch(err => {
  31. store._devtoolHook.emit("vuex:error", err)
  32. throw err
  33. })
  34. } else {
  35. return res
  36. }
  37. })
  38. }

mutation很类似,使用函数包一层然后push到store._actions中,有些不同的是执行时参数比较多,这也是为什么我们在写action时可以解构拿到commit等的原因,然后再将返回值promisify,这样可以支持链式调用,但实际上用的时候最好还是自己返回promise,因为通常action是异步的,比较多见是发起ajax请求,进行链式调用也是想当异步完成后再执行,具体根据业务需求来。接下去再看看dispatch函数的实现

</>复制代码

  1. // this已经绑定为store
  2. dispatch (_type, _payload) {
  3. // 统一格式
  4. const { type, payload } = unifyObjectStyle(_type, _payload)
  5. const action = { type, payload }
  6. // 获取actions数组
  7. const entry = this._actions[type]
  8. // 提示不存在action
  9. if (!entry) {
  10. if (process.env.NODE_ENV !== "production") {
  11. console.error(`[vuex] unknown action type: ${type}`)
  12. }
  13. return
  14. }
  15. // 执行action的订阅者
  16. this._actionSubscribers.forEach(sub => sub(action, this.state))
  17. // 如果action大于1,需要用Promise.all包裹
  18. return entry.length > 1
  19. ? Promise.all(entry.map(handler => handler(payload)))
  20. : entry[0](payload)
  21. }

这里和commit也是很类似的,对参数统一处理,拿到action数组,如果长度大于一,用Promise.all包裹,不过直接执行,然后返回执行结果。

接下去是getters的注册和子module的注册

</>复制代码

  1. /*
  2. * 参数是store、type(namesapce处理后的)、getter函数、module上下文
  3. */
  4. function registerGetter (store, type, rawGetter, local) {
  5. // 不允许重复定义getters
  6. if (store._wrappedGetters[type]) {
  7. if (process.env.NODE_ENV !== "production") {
  8. console.error(`[vuex] duplicate getter key: ${type}`)
  9. }
  10. return
  11. }
  12. // 包一层,保存到_wrappedGetters中
  13. store._wrappedGetters[type] = function wrappedGetter (store) {
  14. // 执行时传入store,执行对应的getter函数
  15. return rawGetter(
  16. local.state, // local state
  17. local.getters, // local getters
  18. store.state, // root state
  19. store.getters // root getters
  20. )
  21. }
  22. }

首先对getters进行判断,和mutation是不同的,这里是不允许重复定义的,然后包裹一层函数,这样在调用时只需要给上store参数,而用户的函数里会包含local.state local.getters store.state store.getters

</>复制代码

  1. // 递归注册子module
  2. installModule(store, rootState, path.concat(key), child, hot)
使用vue实例保存state和getter

接着再继续执行resetStoreVM(this, state),将stategetters存放到一个vue实例中,

</>复制代码

  1. // initialize the store vm, which is responsible for the reactivity
  2. // (also registers _wrappedGetters as computed properties)
  3. resetStoreVM(this, state)

</>复制代码

  1. function resetStoreVM (store, state, hot) {
  2. // 保存旧vm
  3. const oldVm = store._vm
  4. // bind store public getters
  5. store.getters = {}
  6. const wrappedGetters = store._wrappedGetters
  7. const computed = {}
  8. // 循环所有getters,通过Object.defineProperty方法为getters对象建立属性,这样就可以通过this.$store.getters.xxx访问
  9. forEachValue(wrappedGetters, (fn, key) => {
  10. // use computed to leverage its lazy-caching mechanism
  11. // getter保存在computed中,执行时只需要给上store参数,这个在registerGetter时已经做处理
  12. computed[key] = () => fn(store)
  13. Object.defineProperty(store.getters, key, {
  14. get: () => store._vm[key],
  15. enumerable: true // for local getters
  16. })
  17. })
  18. // 使用一个vue实例来保存state和getter
  19. // silent设置为true,取消所有日志警告等
  20. const silent = Vue.config.silent
  21. Vue.config.silent = true
  22. store._vm = new Vue({
  23. data: {
  24. $$state: state
  25. },
  26. computed
  27. })
  28. // 恢复用户的silent设置
  29. Vue.config.silent = silent
  30. // enable strict mode for new vm
  31. // strict模式
  32. if (store.strict) {
  33. enableStrictMode(store)
  34. }
  35. // 若存在oldVm,解除对state的引用,等dom更新后把旧的vue实例销毁
  36. if (oldVm) {
  37. if (hot) {
  38. // dispatch changes in all subscribed watchers
  39. // to force getter re-evaluation for hot reloading.
  40. store._withCommit(() => {
  41. oldVm._data.$$state = null
  42. })
  43. }
  44. Vue.nextTick(() => oldVm.$destroy())
  45. }
  46. }

这里会重新设置一个新的vue实例,用来保存stategettergetters保存在计算属性中,会给getters加一层代理,这样可以通过this.$store.getters.xxx访问到,而且在执行getters时只传入了store参数,这个在上面的registerGetter已经做了处理,也是为什么我们的getters可以拿到state getters rootState rootGetters的原因。然后根据用户设置开启strict模式,如果存在oldVm,解除对state的引用,等dom更新后把旧的vue实例销毁

</>复制代码

  1. function enableStrictMode (store) {
  2. store._vm.$watch(
  3. function () {
  4. return this._data.$$state
  5. },
  6. () => {
  7. if (process.env.NODE_ENV !== "production") {
  8. // 不允许在mutation之外修改state
  9. assert(
  10. store._committing,
  11. `Do not mutate vuex store state outside mutation handlers.`
  12. )
  13. }
  14. },
  15. { deep: true, sync: true }
  16. )
  17. }

使用$watch来观察state的变化,如果此时的store._committing不会true,便是在mutation之外修改state,报错。

再次回到构造函数,接下来是各类插件的注册

2.4 插件注册

</>复制代码

  1. // apply plugins
  2. plugins.forEach(plugin => plugin(this))
  3. if (Vue.config.devtools) {
  4. devtoolPlugin(this)
  5. }

到这里store的初始化工作已经完成。大概长这个样子

看到这里,相信已经对store的一些实现细节有所了解,另外store上还存在一些api,但是用到的比较少,可以简单看看都有些啥

2.5 其他api

watch (getter, cb, options)

用于监听一个getter值的变化

</>复制代码

  1. watch (getter, cb, options) {
  2. if (process.env.NODE_ENV !== "production") {
  3. assert(
  4. typeof getter === "function",
  5. `store.watch only accepts a function.`
  6. )
  7. }
  8. return this._watcherVM.$watch(
  9. () => getter(this.state, this.getters),
  10. cb,
  11. options
  12. )
  13. }

首先判断getter必须是函数类型,使用$watch方法来监控getter的变化,传入stategetters作为参数,当值变化时会执行cb回调。调用此方法返回的函数可停止侦听。

replaceState(state)

用于修改state,主要用于devtool插件的时空穿梭功能,代码也相当简单,直接修改_vm.$$state

</>复制代码

  1. replaceState (state) {
  2. this._withCommit(() => {
  3. this._vm._data.$$state = state
  4. })
  5. }

registerModule (path, rawModule, options = {})

用于动态注册module

</>复制代码

  1. registerModule (path, rawModule, options = {}) {
  2. if (typeof path === "string") path = [path]
  3. if (process.env.NODE_ENV !== "production") {
  4. assert(Array.isArray(path), `module path must be a string or an Array.`)
  5. assert(
  6. path.length > 0,
  7. "cannot register the root module by using registerModule."
  8. )
  9. }
  10. this._modules.register(path, rawModule)
  11. installModule(
  12. this,
  13. this.state,
  14. path,
  15. this._modules.get(path),
  16. options.preserveState
  17. )
  18. // reset store to update getters...
  19. resetStoreVM(this, this.state)
  20. }

首先统一path的格式为Array,接着是断言,path只接受StringArray类型,且不能注册根module,然后调用store._modules.register方法收集module,也就是上面的module-collection里面的方法。再调用installModule进行模块的安装,最后调用resetStoreVM更新_vm

unregisterModule (path)

根据path注销module

</>复制代码

  1. unregisterModule (path) {
  2. if (typeof path === "string") path = [path]
  3. if (process.env.NODE_ENV !== "production") {
  4. assert(Array.isArray(path), `module path must be a string or an Array.`)
  5. }
  6. this._modules.unregister(path)
  7. this._withCommit(() => {
  8. const parentState = getNestedState(this.state, path.slice(0, -1))
  9. Vue.delete(parentState, path[path.length - 1])
  10. })
  11. resetStore(this)
  12. }

registerModule一样,首先统一path的格式为Array,接着是断言,path只接受StringArray类型,接着调用store._modules.unregister方法注销module,然后在store._withCommit中将该modulestate通过Vue.delete移除,最后调用resetStore方法,需要再看看resetStore的实现

</>复制代码

  1. function resetStore (store, hot) {
  2. store._actions = Object.create(null)
  3. store._mutations = Object.create(null)
  4. store._wrappedGetters = Object.create(null)
  5. store._modulesNamespaceMap = Object.create(null)
  6. const state = store.state
  7. // init all modules
  8. installModule(store, state, [], store._modules.root, true)
  9. // reset vm
  10. resetStoreVM(store, state, hot)
  11. }

这里是将_actions _mutations _wrappedGetters _modulesNamespaceMap都清空,然后调用installModuleresetStoreVM重新进行全部模块安装和_vm的设置

_withCommit (fn)

用于执行mutation

</>复制代码

  1. _withCommit (fn) {
  2. const committing = this._committing
  3. this._committing = true
  4. fn()
  5. this._committing = committing
  6. }

在执行mutation的时候,会将_committing设置为true,执行完毕后重置,在开启strict模式时,会监听state的变化,当变化时_committing不为true时会给出警告

3. 辅助函数

为了避免每次都需要通过this.$store来调用api,vuex提供了mapState mapMutations mapGetters mapActions createNamespacedHelpers 等api,接着看看各api的具体实现,存放在src/helpers.js

3.1 一些工具函数

下面这些工具函数是辅助函数内部会用到的,可以先看看功能和实现,主要做的工作是数据格式的统一、和通过namespace获取module

</>复制代码

  1. /**
  2. * 统一数据格式
  3. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  4. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: "a", val: 1 }, { key: "b", val: 2 }, { key: "c", val: 3 } ]
  5. * @param {Array|Object} map
  6. * @return {Object}
  7. */
  8. function normalizeMap (map) {
  9. return Array.isArray(map)
  10. ? map.map(key => ({ key, val: key }))
  11. : Object.keys(map).map(key => ({ key, val: map[key] }))
  12. }
  13. /**
  14. * 返回一个函数,接受namespacemap参数,判断是否存在namespace,统一进行namespace处理
  15. * @param {Function} fn
  16. * @return {Function}
  17. */
  18. function normalizeNamespace (fn) {
  19. return (namespace, map) => {
  20. if (typeof namespace !== "string") {
  21. map = namespace
  22. namespace = ""
  23. } else if (namespace.charAt(namespace.length - 1) !== "/") {
  24. namespace += "/"
  25. }
  26. return fn(namespace, map)
  27. }
  28. }
  29. /**
  30. * 根据namespace获取module
  31. * @param {Object} store
  32. * @param {String} helper
  33. * @param {String} namespace
  34. * @return {Object}
  35. */
  36. function getModuleByNamespace (store, helper, namespace) {
  37. const module = store._modulesNamespaceMap[namespace]
  38. if (process.env.NODE_ENV !== "production" && !module) {
  39. console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
  40. }
  41. return module
  42. }
3.2 mapState

为组件创建计算属性以返回 store 中的状态

</>复制代码

  1. export const mapState = normalizeNamespace((namespace, states) => {
  2. const res = {}
  3. normalizeMap(states).forEach(({ key, val }) => {
  4. // 返回一个对象,值都是函数
  5. res[key] = function mappedState () {
  6. let state = this.$store.state
  7. let getters = this.$store.getters
  8. if (namespace) {
  9. // 如果存在namespace,拿该namespace下的module
  10. const module = getModuleByNamespace(this.$store, "mapState", namespace)
  11. if (!module) {
  12. return
  13. }
  14. // 拿到当前module的state和getters
  15. state = module.context.state
  16. getters = module.context.getters
  17. }
  18. // Object类型的val是函数,传递过去的参数是state和getters
  19. return typeof val === "function"
  20. ? val.call(this, state, getters)
  21. : state[val]
  22. }
  23. // mark vuex getter for devtools
  24. res[key].vuex = true
  25. })
  26. return res
  27. })

mapStatenormalizeNamespace的返回值,从上面的代码可以看到normalizeNamespace是进行参数处理,如果存在namespace便加上命名空间,对传入的states进行normalizeMap处理,也就是数据格式的统一,然后遍历,对参数里的所有state都包裹一层函数,最后返回一个对象

大概是这么回事吧

</>复制代码

  1. export default {
  2. // ...
  3. computed: {
  4. ...mapState(["stateA"])
  5. }
  6. // ...
  7. }

等价于

</>复制代码

  1. export default {
  2. // ...
  3. computed: {
  4. stateA () {
  5. return this.$store.stateA
  6. }
  7. }
  8. // ...
  9. }
3.4 mapGetters

store 中的 getter 映射到局部计算属性中

</>复制代码

  1. export const mapGetters = normalizeNamespace((namespace, getters) => {
  2. const res = {}
  3. normalizeMap(getters).forEach(({ key, val }) => {
  4. // this namespace has been mutate by normalizeNamespace
  5. val = namespace + val
  6. res[key] = function mappedGetter () {
  7. if (namespace && !getModuleByNamespace(this.$store, "mapGetters", namespace)) {
  8. return
  9. }
  10. if (process.env.NODE_ENV !== "production" && !(val in this.$store.getters)) {
  11. console.error(`[vuex] unknown getter: ${val}`)
  12. return
  13. }
  14. return this.$store.getters[val]
  15. }
  16. // mark vuex getter for devtools
  17. res[key].vuex = true
  18. })
  19. return res
  20. })

同样的处理方式,遍历getters,只是这里需要加上命名空间,这是因为在注册时_wrapGetters中的getters是有加上命名空间的

3.4 mapMutations

创建组件方法提交 mutation

</>复制代码

  1. export const mapMutations = normalizeNamespace((namespace, mutations) => {
  2. const res = {}
  3. normalizeMap(mutations).forEach(({ key, val }) => {
  4. // 返回一个对象,值是函数
  5. res[key] = function mappedMutation (...args) {
  6. // Get the commit method from store
  7. let commit = this.$store.commit
  8. if (namespace) {
  9. const module = getModuleByNamespace(this.$store, "mapMutations", namespace)
  10. if (!module) {
  11. return
  12. }
  13. commit = module.context.commit
  14. }
  15. // 执行mutation,
  16. return typeof val === "function"
  17. ? val.apply(this, [commit].concat(args))
  18. : commit.apply(this.$store, [val].concat(args))
  19. }
  20. })
  21. return res
  22. })

和上面都是一样的处理方式,这里在判断是否存在namespace后,commit是不一样的,上面可以知道每个module都是保存了上下文的,这里如果存在namespace就需要使用那个另外处理的commit等信息,另外需要注意的是,这里不需要加上namespace,这是因为在module.context.commit中会进行处理,忘记的可以往上翻,看makeLocalContextcommit的处理

3.5 mapAction

创建组件方法分发 action

</>复制代码

  1. export const mapActions = normalizeNamespace((namespace, actions) => {
  2. const res = {}
  3. normalizeMap(actions).forEach(({ key, val }) => {
  4. res[key] = function mappedAction (...args) {
  5. // get dispatch function from store
  6. let dispatch = this.$store.dispatch
  7. if (namespace) {
  8. const module = getModuleByNamespace(this.$store, "mapActions", namespace)
  9. if (!module) {
  10. return
  11. }
  12. dispatch = module.context.dispatch
  13. }
  14. return typeof val === "function"
  15. ? val.apply(this, [dispatch].concat(args))
  16. : dispatch.apply(this.$store, [val].concat(args))
  17. }
  18. })
  19. return res
  20. })

mapMutations基本一样的处理方式

4. 插件

Vuex中可以传入plguins选项来安装各种插件,这些插件都是函数,接受store作为参数,Vuex中内置了devtoollogger两个插件,

</>复制代码

  1. // 插件注册,所有插件都是一个函数,接受store作为参数
  2. plugins.forEach(plugin => plugin(this))
  3. // 如果开启devtools,注册devtool
  4. if (Vue.config.devtools) {
  5. devtoolPlugin(this)
  6. }

</>复制代码

  1. // devtools.js
  2. const devtoolHook =
  3. typeof window !== "undefined" &&
  4. window.__VUE_DEVTOOLS_GLOBAL_HOOK__
  5. export default function devtoolPlugin (store) {
  6. if (!devtoolHook) return
  7. store._devtoolHook = devtoolHook
  8. // 触发vuex:init
  9. devtoolHook.emit("vuex:init", store)
  10. // 时空穿梭功能
  11. devtoolHook.on("vuex:travel-to-state", targetState => {
  12. store.replaceState(targetState)
  13. })
  14. // 订阅mutation,当触发mutation时触发vuex:mutation方法,传入mutation和state
  15. store.subscribe((mutation, state) => {
  16. devtoolHook.emit("vuex:mutation", mutation, state)
  17. })
  18. }
总结

到这里基本vuex的流程源码已经分析完毕,分享下自己看源码的思路或者过程,在看之前先把官网的文档再仔细过一遍,然后带着问题来看源码,这样效率会比较高,利用chrome在关键点打开debugger,一步一步执行,看源码的执行过程,数据状态的变换。而且可以暂时屏蔽一些没有副作用的代码,比如assert,这些函数一般都不会影响流程的理解,这样也可以尽量减少源码行数。剩下的就是耐心了,前前后后断断续续看了很多次,总算也把这份分享写完了,由于水平关系,一些地方可能理解错误或者不到位,欢迎指出。

原文地址

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

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

相关文章

  • vuex源码阅读分析

    摘要:继续看后面的首先遍历的,通过和首先获取然后调用方法,我们来看看是不是感觉这个函数有些熟悉,表示当前实例,表示类型,表示执行的回调函数,表示本地化后的一个变量。必须是一个函数,如果返回的值发生了变化,那么就调用回调函数。 这几天忙啊,有绝地求生要上分,英雄联盟新赛季需要上分,就懒着什么也没写,很惭愧。这个vuex,vue-router,vue的源码我半个月前就看的差不多了,但是懒,哈哈。...

    gplane 评论0 收藏0
  • vuex源码阅读分析

    摘要:继续看后面的首先遍历的,通过和首先获取然后调用方法,我们来看看是不是感觉这个函数有些熟悉,表示当前实例,表示类型,表示执行的回调函数,表示本地化后的一个变量。必须是一个函数,如果返回的值发生了变化,那么就调用回调函数。 这几天忙啊,有绝地求生要上分,英雄联盟新赛季需要上分,就懒着什么也没写,很惭愧。这个vuex,vue-router,vue的源码我半个月前就看的差不多了,但是懒,哈哈。...

    airborne007 评论0 收藏0
  • Vuex源码阅读笔记

    摘要:而钻研最好的方式,就是阅读的源代码。整个的源代码,核心内容包括两部分。逃而动手脚的代码,就存在于源代码的中。整个源代码读下来一遍,虽然有些部分不太理解,但是对和一些代码的使用的理解又加深了一步。 笔记中的Vue与Vuex版本为1.0.21和0.6.2,需要阅读者有使用Vue,Vuex,ES6的经验。 起因 俗话说得好,没有无缘无故的爱,也没有无缘无故的恨,更不会无缘无故的去阅读别人的源...

    hosition 评论0 收藏0
  • 前方来报,八月最新资讯--关于vue2&3的最佳文章推荐

    摘要:哪吒别人的看法都是狗屁,你是谁只有你自己说了才算,这是爹教我的道理。哪吒去他个鸟命我命由我,不由天是魔是仙,我自己决定哪吒白白搭上一条人命,你傻不傻敖丙不傻谁和你做朋友太乙真人人是否能够改变命运,我不晓得。我只晓得,不认命是哪吒的命。 showImg(https://segmentfault.com/img/bVbwiGL?w=900&h=378); 出处 查看github最新的Vue...

    izhuhaodev 评论0 收藏0
  • 前端阅读笔记 2016-11-25

    摘要:为了防止某些文档或脚本加载别的域下的未知内容,防止造成泄露隐私,破坏系统等行为发生。模式构建函数响应式前端架构过程中学到的经验模式的不同之处在于,它主要专注于恰当地实现应用程序状态突变。严重情况下,会造成恶意的流量劫持等问题。 今天是编辑周刊的日子。所以文章很多和周刊一样。微信不能发链接,点了也木有用,所以请记得阅读原文~ 发个动图娱乐下: 使用 SVG 动画制作游戏 使用 GASP ...

    KoreyLee 评论0 收藏0

发表评论

0条评论

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