vuex 源码解读

大憨熊 提交于 2019-11-29 03:20:15

首先让我们看一下,vuex的基本使用

import Vuex from 'vuex'
import cart from './modules/cart'
import products from './modules/products'
import createLogger from '../../../src/plugins/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
  modules: {
    cart,
    products
  },
  strict: debug,
  plugins: debug ? [createLogger()] : []
})```

由于使用了use方法,可看出vuex是个插件, 那我们就先看,vuex源码的install 方法,以下代码节选至vue源码index.js和mixin.js中。

// index.js中install 方法
applyMixin(Vue)
mixin.js
Vue.mixin({ beforeCreate: vuexInit })
function vuexInit () {
    const options = this.$options
    // store injection
    if (options.store) {
      this.$store = typeof options.store === 'function'
        ? options.store()
        : options.store
    } else if (options.parent && options.parent.$store) {
      this.$store = options.parent.$store
    }
  }

看上面代码,其实 install 方法只做了一件事,就是利用全局混入在beforeCreate生命周期中,给所有实例添加了$store方法,指向根store。所以我们在vue页面可以通过this.$store访问到根状态 install方法看完了,我们就看一下,constructor 初始化方法 这里面主要是定义一些起始变量,重点看下以下几个方法做了什么

this._modules = new ModuleCollection(options) // 重新组装了传过来的参数
this._watcherVM = new Vue() // 重新new了一个vue 对象,来做观察订阅者
installModule(this, state, [], this._modules.root) // 调用 vue.set 方法,把模块化数据,添加到VUE的响应式系统中
resetStoreVM(this, state) 初始化了一个_vm对象,指向一个新的new实例, 把跟state赋给data ,定义一个computed。
然后定义了一个 
get state () {
    return this._vm._data.$$state
 }
 我们this.$store.state,取数据,全都通过了_vm新实例的代理访问

源码的最后一行就是 vuex插件了,

if (useDevtools) {
      devtoolPlugin(this)
    }

vuex 插件,就是一个函数,接收 vuex实例作为唯一的参数,里面有个 store.subscribe((mutation, state) => {}) 方法,会在每次mutation后调用, 注:使用module化的时候,要注意开启命名空间, namespaced: true, 不然模块内方法名重复会都执行,开启后,通过‘moduleName/methodsName’,访问

主要参考vuex 源码和官方文档解释

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!