Vuex源码探究

803 阅读5分钟

之前在项目中有使用过Vuex做状态管理器,但是一直没有了解Vuex的工作原理。鉴于学习一门技术必须掌握其原理的基础,现在我们来探究下Vuex的源码。

Vuex 官方github仓库地址

我们将仓库克隆到本地:

git clone https://github.com/vuejs/vuex

Vuex源码存放在src目录中,包含以下内容:

  1. module - Vuex modules 相关内容(暂不做分析)
  2. plugins - 自带plugin插件
  3. helper - 包含 mapState,mapMutations等工具类方法
  4. index.js - Vuex入口文件
  5. mixins - Vuex初始化操作与Vue 1.x版本兼容性处理
  6. store.js - Vuex.store相关逻辑
  7. util.js - 内部工具类

我们先来回顾下Vuex主要流程:

这张图很直观的反映了Vuex的工作流程:

  1. 视图层触发action(mutation)
  2. mutation负责修改store状态
  3. store状态同步到视图层

一个基本的Vuex应该包含以下几个部分:

  1. 初始化Store类
  2. 存储和绑定mutations和actions
  3. 实现dispatch和commit方法

Vuex安装

我们一般使用如下方法安装Vuex:

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

new Vue({
    store:new Vuex.Store({
        ...
    })
})

Vue提供了Vue.use方法来安装第三方插件,实际内部是通过调用插件对外暴露出来的install来完成的。同样Vuex也提供了install方法:

export function install (_Vue) {
  if (Vue && _Vue === Vue) {
    if (process.env.NODE_ENV !== 'production') {
      console.error(
        '[vuex] already installed. Vue.use(Vuex) should be called only once.'
      )
    }
    return
  }
  Vue = _Vue
  applyMixin(Vue)
}

这里使用 _Vue === Vue巧妙的判断了是否之前已经初始过Vuex,之后调用applyMixin函数。applyMixin被定义在了mixin.js中。

export default function (Vue) {
  const version = Number(Vue.version.split('.')[0])

  if (version >= 2) {
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // override init and inject vuex init procedure
    // for 1.x backwards compatibility.
    const _init = Vue.prototype._init
    Vue.prototype._init = function (options = {}) {
      options.init = options.init
        ? [vuexInit].concat(options.init)
        : vuexInit
      _init.call(this, options)
    }
  }

  /**
   * Vuex init hook, injected into each instances init hooks list.
   */

  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
    }
  }
}

这里首先在内部屏蔽了Vue1.0和2.0的版本差异,对不同版本使用了不同的方法去对每一个Vue实例注册$store对象。在2.0版本中使用了Vue.mixin全局注册混入,在beforeCreate生命周期函数中向this注入了$store对象。这里首先会判断当前组件是否是根组件,如果是根组件则直接注入;如果非根组件,通过options中的parent访问父组件的store引用。这样,我们就可以在所有组件中都获取到同一个引用的 store 对象了。 能访问到$store对象了。

Store类实现

class Store {
    constructor(options = {}) {
    const {
      plugins = [],
      strict = false
    } = options

    // store internal state
    this._committing = false
    this._actions = Object.create(null)
    this._actionSubscribers = []
    this._mutations = Object.create(null)
    this._wrappedGetters = Object.create(null)
    this._modules = new ModuleCollection(options)
    this._modulesNamespaceMap = Object.create(null)
    this._subscribers = []
    this._watcherVM = new Vue()

    // bind commit and dispatch to self
    const store = this
    const { dispatch, commit } = this
    this.dispatch = function boundDispatch (type, payload) {
      return dispatch.call(store, type, payload)
    }
    this.commit = function boundCommit (type, payload, options) {
      return commit.call(store, type, payload, options)
    }

    const state = this._modules.root.state
    
    installModule(this, state, [], this._modules.root)

    //执行所有plugin
    plugins.forEach(plugin => plugin(this))

    }

  }
}

在Store的构造函数中,新建以下属性:

  1. _actions
  2. _mutations
  3. _actionSubscribers
  4. _wrappedGetters
  5. _modules
  6. _subscribers
  7. _watcherVM
  • _actions存储我们实例化Store对象时传入的action
  • _mutation存储我们实例化Store对象时传入的mutation
  • _actionSubscribers中存放外部定义对action的订阅
  • _subscribers中存放外部定义的对mutation的订阅
  • wrappedGetters中定义了外部传入的getter
  • _modules定义了外部传入的modules
  • _watchVM是一个Vue的实例对象,用于对外部传入的getter进行依赖收集

在初始化变量完成后,主要调用了 installModules (初始化module) 和 resetStoreVM (通过Vue使store做到响应式)。

installModule

function installModule (store, rootState, path, module, hot) {
  const isRoot = !path.length
  const namespace = store._modules.getNamespace(path)

  // register in namespace map
  if (module.namespaced) {
    if (store._modulesNamespaceMap[namespace] && process.env.NODE_ENV !== 'production') {
      console.error(`[vuex] duplicate namespace ${namespace} for the namespaced module ${path.join('/')}`)
    }
    store._modulesNamespaceMap[namespace] = module
  }

  // set state
  if (!isRoot && !hot) {
    const parentState = getNestedState(rootState, path.slice(0, -1))
    const moduleName = path[path.length - 1]
    store._withCommit(() => {
      Vue.set(parentState, moduleName, module.state)
    })
  }

  const local = module.context = makeLocalContext(store, namespace, path)

  module.forEachMutation((mutation, key) => {
    const namespacedType = namespace + key
    registerMutation(store, namespacedType, mutation, local)
  })

  module.forEachAction((action, key) => {
    const type = action.root ? key : namespace + key
    const handler = action.handler || action
    registerAction(store, type, handler, local)
  })

  module.forEachGetter((getter, key) => {
    const namespacedType = namespace + key
    registerGetter(store, namespacedType, getter, local)
  })

  module.forEachChild((child, key) => {
    installModule(store, rootState, path.concat(key), child, hot)
  })
}

installModule作用是为module加上命名空间后,注册 mutation、action 和 getter,同时递归安装所有子 module。

resetStoreVM

function resetStoreVM (store, state, hot) {
  const oldVm = store._vm

  // bind store public getters
  store.getters = {}
  const wrappedGetters = store._wrappedGetters
  const computed = {}
  forEachValue(wrappedGetters, (fn, key) => {
    // use computed to leverage its lazy-caching mechanism
    // direct inline function use will lead to closure preserving oldVm.
    // using partial to return function with only arguments preserved in closure enviroment.
    computed[key] = partial(fn, store)
    Object.defineProperty(store.getters, key, {
      get: () => store._vm[key],
      enumerable: true // for local getters
    })
  })

  // use a Vue instance to store the state tree
  // suppress warnings just in case the user has added
  // some funky global mixins
  const silent = Vue.config.silent
  Vue.config.silent = true
  store._vm = new Vue({
    data: {
      ?state: state
    },
    computed
  })
  Vue.config.silent = silent

  // enable strict mode for new vm
  if (store.strict) {
    enableStrictMode(store)
  }

  if (oldVm) {
    if (hot) {
      // dispatch changes in all subscribed watchers
      // to force getter re-evaluation for hot reloading.
      store._withCommit(() => {
        oldVm._data.?state = null
      })
    }
    Vue.nextTick(() => oldVm.$destroy())
  }
}

这里会先遍历所有 wrappedGetters ,然后将每个元素使用 Object.defineProperty 方法添加 getter,使我们在外部可以使用 this.$store.getter.count 这种方式访问 getter。之后 实例化一个Vue对象,利用Vue的响应式做数据更新。

commit

commit (_type, _payload, _options) {
    // check object-style commit
    const {
      type,
      payload,
      options
    } = unifyObjectStyle(_type, _payload, _options)

    const mutation = { type, payload }
    const entry = this._mutations[type]
    if (!entry) {
      if (process.env.NODE_ENV !== 'production') {
        console.error(`[vuex] unknown mutation type: ${type}`)
      }
      return
    }
    this._withCommit(() => {
      entry.forEach(function commitIterator (handler) {
        handler(payload)
      })
    })
    this._subscribers.forEach(sub => sub(mutation, this.state))

    if (
      process.env.NODE_ENV !== 'production' &&
      options && options.silent
    ) {
      console.warn(
        `[vuex] mutation type: ${type}. Silent option has been removed. ` +
        'Use the filter functionality in the vue-devtools'
      )
    }
  }

  

由于commit函数可以传入不同数据格式的参数,所以这里用unifyObjectStyle 将多种传入的数据格式转换成相同的格式去处理。 commit被触发后,在this._mutations中查找对应类型的handlers,找到之后将所有匹配到的handlers执行并且传入payload。在执行handlers前后还会触发一些subscribe中定义的beforeafter钩子函数,关于 subscribe这里我们举个例子:

var myPlugin = store => {
  store.subscribe(function (mutation, state) {
    // Do something...
  })
}

在定义插件的过程中,我们常常需要监听多个mutation,在mutation触发之后做一些公共的操作,比如记录日志之类的,这时候我们就可以使用以上代码来实现。

dispatch

dispatch (_type, _payload) {
    // check object-style dispatch
    // //处理传入的多种数据格式
    const {
      type,
      payload
    } = unifyObjectStyle(_type, _payload)

    const action = { type, payload }
    const entry = this._actions[type]
    if (!entry) {
      if (process.env.NODE_ENV !== 'production') {
        console.error(`[vuex] unknown action type: ${type}`)
      }
      return
    }

    try {
      this._actionSubscribers
        .filter(sub => sub.before)
        .forEach(sub => sub.before(action, this.state))
    } catch (e) {
      if (process.env.NODE_ENV !== 'production') {
        console.warn(`[vuex] error in before action subscribers: `)
        console.error(e)
      }
    }
    //查找对应action type的 handler方法,如果找到则批量执行handler方法
    const result = entry.length > 1
      ? Promise.all(entry.map(handler => handler(payload)))
      : entry[0](payload)

    return result.then(res => {
      try {
        this._actionSubscribers
          .filter(sub => sub.after)
          .forEach(sub => sub.after(action, this.state))
      } catch (e) {
        if (process.env.NODE_ENV !== 'production') {
          console.warn(`[vuex] error in after action subscribers: `)
          console.error(e)
        }
      }
      return res
    })
  }

dispatch实现与commit类似,不同的地方在于 dispatch中需要进行异步操作,这里使用 Promise.all 来触发对应action的handler,然后返回Promise。

watch

watch方法的实现使通过实例一个Vue对象,并调用Vue.prototype.$watch做数据变动监听。

this._watcherVM = new Vue()//创建Vue实例
watch (getter, cb, options) {
    if (process.env.NODE_ENV !== 'production') {
      assert(typeof getter === 'function', `store.watch only accepts a function.`)
    }
    return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options)
}

registerMutation

registreMuation的作用是将各个module下面的mutation注册,在 installModule 中会调用此函数。

registerAction

registerAction的作用与registerMutation类似,是把各个module下面的action注册。这里与registerMutation不同的是会判断action执行后返回的是否是Promise对象,如果不是则会将执行结果转换为 resolved状态的Promise对象。

Vuex基本功能实现

根据上面对Vuex源码的理解,我们来实现一个具有最基本功能的Vuex。

let Vuex = {};
let Vue = null;
function transformType(type,payload,options) {
	if(type!==null && typeof type == 'object') {
		payload = type;
		type = type.type;
	}
	return {type,payload,options}
}

class Store {
	constructor(options) {
		this.actions = options.actions || Object.create(null);
		this.mutations = options.mutations || Object.create(null);
		this._vm = new Vue({
			data() {
				return {
					state:options.state
				}
			}
		})
	}

	get state() {
		return this._vm._data.state;
	}

	set state(v) {
		console.error('[vuex]:state不能被直接修改,必须通过mutation进行修改')
	}

	commit(_type,_payload,_options) {
		const {type,payload,options} = transformType(_type,_payload,_options);
		Object.keys(this.mutations).forEach(mutation=>{
			let handler = this.mutations[mutation];
			if(mutation===type && typeof handler == 'function') {
				handler.call(this,this.state,payload);
			}
		})
	}

	dispatch(_type,_payload,_options) {
		let p;
		const {type,payload,options} = transformType(_type,_payload,_options);
		Object.keys(this.actions).forEach(action=>{
			let handler = this.actions[action];
			if(action===type && typeof handler == 'function') {
				p = handler.call(this,this,payload,options);
			}
		})
		return p;
	}
}


Vuex.Store = Store;


Vuex.install = function(_Vue,options) {
	//仅支持Vue2.x版本
	if(Vue && Vue===_Vue) {
		console.error('Vuex已经注册!');
		return;
	}
	Vue = _Vue;
	Vue.mixin({
		beforeCreate() {
			const options = this.$options;
			if(options.store) {
				//只有根组件才会有store配置。如果是根组件,直接将options.store绑定到this.$store上面
				this.$store = typeof options.store == 'function'?options.store():options.store;
			} else if(options.parent && options.parent.$store){
				//如非根组件,则从其父级获得store,绑定到自身$store上面
				this.$store = options.parent.$store;
			}
		}
	})
}


module.exports = Vuex;

单元测试

上面我们实现了最基本的Vuex,但是无法验证其功能是否正确或者符合我们的要求。下面我们使用mocha+chai做个单元测试,确保我们的功能没有问题。 我们首先来安装依赖:

yarn add mocha chai Vue -D

安装完依赖后我们进行用例编写:

const should = require('chai').should();
const Vue  = require('vue');
const Vuex = require('../src/store.js');
Vue.use(Vuex)
describe('测试Vuex基本功能',function() {
	vm = new Vue({
		store:new Vuex.Store({
			state:{
				count:1
			},
			mutations:{
				add(state,payload) {
					state.count+=payload
				}
			},
			actions:{
				change(context,payload) {
					return new Promise(function(resolve,reject){
						setTimeout(()=>{
							context.commit('add',payload)
							resolve()
						},2000)
					})
				}
			}
		})
	})


	it('测试Vuex安装是否正常',function() {
		should.exist(vm.$store)
	})
	it('测试state是否正常初始化',function() {
		vm.$store.state.count.should.to.equal(1)
	})
	it('测试mutation是否正常提交',function(){
		vm.$store.commit('add',2)
		vm.$store.state.count.should.to.equal(3);
	})
	it('测试action是否正常提交',function() {
		vm.$store.dispatch('change',3).then(()=>{
			vm.$store.state.count.should.equal(6);
		})
	})
})

总结

Vuex的运行原理已经有所了解并且我们已经实现了一个最基本的Vuex。学习Vuex源码的关键就是了解Vuex的运行过程以及应用场景,这样我们在开发过程中就可以随心所欲地使用Vuex了。

以下是参考文章列表:

  1. vuex.vuejs.org/zh/guide/
  2. cn.vuejs.org/
  3. www.cnblogs.com/answershuto…