生命周期的合并
1.Mixin原理
import { mergeOptions } from '../utils/index';
export function initGlobalApi(Vue) {
Vue.options = {};
Vue.Mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
};
}
2.合并生命周期
export const HOOKS = ['beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed'];
export function mergeOptions(parent, child) {
const options = {};
let starts = {};
starts.data = function (parentVal, childVal) {
return childVal;
};
starts.watch = function () {};
starts.methods = function () {};
starts.computed = function () {};
HOOKS.forEach((key) => {
starts[key] = mergeHooks;
});
function mergeHooks(parentVal, childVal) {
if (childVal) {
if (parentVal) {
return parentVal.concat(childVal);
}
return [childVal];
} else {
return [parentVal];
}
}
for (const key in parent) {
mergeField(key);
}
for (const key in child) {
mergeField(key);
}
function mergeField(key) {
if (starts[key]) {
options[key] = starts[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.初始化流程中调用生命周期
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);
}
}