Vue中常用合并对象的方法
vue的生命周期的合并
let lifeCycleHooks=[
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestory',
'destoryed'
]
let strats={};
// 存放着各种策略
function mergeHook(parentVal,childVal) {
if(childVal){
if(parentVal){
return parentVal.concat(childVal);
// concat
}else{
return [childVal]
}
}else{
return parentVal;
}
}
lifeCycleHooks.forEach(hook=>{
strats[hook]=mergeHook
})
function isObject(val){
return typeof val=='object' && val !==null;
}
function mergeOptions(parent,child){
const options={};
for(let key in parent){
mergeField(key);
}
function mergeField(key){
let parentVal=parent[key];
let childVal=child[key];
// 如果有对应的策略 就调用对应的策略即可
if(strats[key]){
options=strats[key](parentVal,childVal)
}else{
if(isObject(parentVal) && isObject(childVal)){
options[key]={...parentVal,...childVal}
}else{
options[key]=child[key];
}
}
}
return options;
}
//console.log(mergeOptions({a:1,data:{a:1}},{data:{b:2},a:100}));
console.log(mergeOptions({beforeCreate:[()=>{}]},{beforeCreate(){}} ));