Vuex注入
Vuex
是作为vue
的一个插件而存在的,它只能应用在vue
中,是因为其高度依赖vue
中的computed
依赖检测系统以及其插件系统。
在vue
中,每一个插件都需要一个公开的install
方法,在vuex
中,它的install
方法中调用了applyMixin
方法。这个方法的主要作用是在所有组件的beforeCreate
生命周期中注入this.$store
这样一个对象。源码如下:
// src/store.js
export function install (_Vue) {
if (Vue && _Vue === Vue) {
if (__DEV__) {
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
)
}
return
}
Vue = _Vue
applyMixin(Vue)
}
// src/mixin.js
// 对应的applyMinix方法
export default function (Vue) {
const version = Number(Vue.version.split('.')[0])
if (version >= 2) {
// vue版本大于2使用混入的方式,在每个组件的beforeCreate生命周期中混入vuexInit函数
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