浅谈Vuex注入Vue生命周期的过程

2020-06-12 21:16:22易采站长站整理

/* 判断插件是否有 install 方法 */
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}

这段代码主要做了两件事情:

一件是防止重复安装相同的 plugin
另一件是初始化 plugin

插件的 install 方法

看完以上源码,我们知道插件(Vuex)需要提供一个

install
方法。那么我们看看 Vuex 源码中是否有这个方法。结果当然是有的:


/* 暴露给外部的 install 方法 */
function install (_Vue) {
/* 避免重复安装(Vue.use 内部也会检测一次是否重复安装同一个插件)*/
if (Vue && _Vue === Vue) {
{
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
);
}
return
}
Vue = _Vue;
/* 将 vuexInit 混淆进 Vue 的 beforeCreate(Vue2.0) 或 _init 方法(Vue1.0) */
applyMixin(Vue);
}

这段代码主要做了两件事情:

一件是防止 Vuex 被重复安装
另一件是执行

applyMixin
,目的是执行
vuexInit
方法初始化 Vuex

接下来 我们看看

applyMixin(Vue)
源码:


/* 将 vuexInit 混淆进 Vue 的 beforeCreate */
function applyMixin (Vue) {
var version = Number(Vue.version.split('.')[0]);
if (version >= 2) {
Vue.mixin({ beforeCreate: vuexInit });
} else {
/* Vue1.0 的处理逻辑,此处省略 */
......
}
function vuexInit () {
......
}
}

从上面的源码,可以看出

Vue.mixin
方法将
vuexInit
方法混淆进
beforeCreate
钩子中,也是因为这个操作,所以每一个 vm 实例都会调用
vuexInit
方法。那么
vuexInit
又做了什么呢?

vuexInit()

我们在使用 Vuex 的时候,需要将 store 传入到 Vue 实例中去。


new Vue({
el: '#app',
store
});

但是我们却在每一个 vm 中都可以访问该 store,这个就需要靠

vuexInit
了。


function vuexInit () {
const options = this.$options
if (options.store) {
/* 根节点存在 stroe 时 */
this.$store = typeof options.store === 'function'