生命周期的合并
1.Mixin原理
import {mergeOptions} from '../util/index.js'
export function initGlobalAPI(Vue){
Vue.options = {};
Vue.mixin = function (mixin) {
// 将属性合并到Vue.options上
this.options = mergeOptions(this.options,mixin);
return this;
}
}
2.合并生命周期
export const LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
]
const strats = {};
function mergeHook(parentVal, childValue) {
if (childValue) {
if (parentVal) {
return parentVal.concat(childValue);
} else {
return [childValue]
}
} else {
return parentVal;
}
}
LIFECYCLE_HOOKS.forEach(hook => {
strats[hook] = mergeHook
})
export function mergeOptions(parent, child) {
const options = {}
for (let key in parent) {
mergeField(key)
}
for (let key in child) {
if (!parent.hasOwnProperty(key)) {
mergeField(key);
}
}
function mergeField(key) {
if (strats[key]) {
options[key] = strats[key](parent[key], child[key]);
} else {
if (typeof parent[key] == 'object' && typeof child[key] == 'object') {
options[key] = {
...parent[key],
...child[key]
}
}else{
options[key] = child[key];
}
}
}
return options
}
4.调用生命周期
export function callHook(vm, hook) {
const handlers = vm.$options[hook];
if (handlers) {
for (let i = 0; i < handlers.length; i++) {
handlers[i].call(vm);
}
}
}
5.初始化流程中调用生命周期
init.js
Vue.prototype._init = function (options) {
const vm = this;
vm.$options = mergeOptions(vm.constructor.options,options);
// 初始化状态
callHook(vm,'beforeCreate');
initState(vm);
callHook(vm,'created');
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
}