VueX作为状态管理工具,其优点就不在此赘述了。源码分析的第一章节只是分析如何引入vuex。
首先,我们先来看一下vuex的使用。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
});
其中最重要的两行代码就是Vue.use(vuex) 以及 new Vuex.Store({options})。
- Vue.use(Vuex) 分析
Vue.use方法封装是在vue\src\core\global-api\use.js,代码如下,中心思想只是去触发插件里的install方法或者插件本身(如果插件本身是方法)
/* @flow */
import { toArray } from '../util/index'
export function initUse(Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
// 判断该插件是否已安装,若已安装直接return
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// 这里处理新增的参数,排除plugin参数
const args = toArray(arguments, 1)
// 此处新增Vue参数
args.unshift(this)
// 插件存在install方法,触发install方法
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args) // 传入plugin和vue两个参数
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
上面我们已经分析到Vue.use方法实际只是去触发插件(我们这里是VueX)的install方法或自身,所以接下来我们去VueX下找下是否有install方法。(代码路径: \vuex\dist\vuex.js)
Bingo,我们找到了install方法,不难理解,该方法只是判断了是否已经安装了vuex,如若没有就赋值给Vue且混合Vue。
function install (_Vue) {
if (Vue && _Vue === Vue) {
{
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
);
}
return
}
Vue = _Vue;
applyMixin(Vue);
}
最后我们发现整个vuex.js 只是抛出了如下内容, 所以我们引入的VueX具体内容就是下面的对象。
var index_esm = {
Store: Store,
install: install,
version: '3.1.3',
mapState: mapState,
mapMutations: mapMutations,
mapGetters: mapGetters,
mapActions: mapActions,
createNamespacedHelpers: createNamespacedHelpers
};
export default index_esm;
- new VueX.Store({})
从上图VueX.PNG更直观的显示VueX.Store是个方法,所以我们又可以去vuex.js中找寻Store方法。
var Store = function Store(options) {}
写这篇文章本意是为了督促自己多看源码多学习多记录,写的比较粗糙,如有错误,麻烦各位大佬指正。
网友评论