问题描述
更新
添加在线代码笔。.
https://codepen.io/jiaxi0331/pen/xxVZBMz
说明
无法通过调用递归方法调用父方法
代码
export default {
methods: {
dispatch(componentName,event,value) {
if (this.$options.name === componentName) {
this.$emit(event,value);
} else {
const parent = this.$parent || this.$root;
return this.dispatch.call(parent,componentName,value); // Error. call this.dispatch in component.
}
}
// broadcast(componentName,value) {}
},};
预期&&详细错误
dispatch.call(parent)-> parent.dispatch.call(parent.parent)-> parent.parent.dispatch ...
详细错误:
Error in v-on handler: "RangeError: Maximum call stack size exceeded"
版本
vue 2.6.1
尝试
function dispatch(componentName,value) {
if (this.$options.name === componentName) {
this.$emit(event,value);
} else {
const parent = this.$parent || this.$root;
return dispatch.call(parent,value);
}
}
export default {
methods: {
dispatch(componentName,value) {
dispatch.call(this,value);
}
// broadcast(componentName,value) {}
}
};
它起作用了,我知道原因是dispatch.call(this。$ parent)更改了此对象,但是为什么this.dispatch.call(this。$ parent)失败了?
解决方法
问题在这里:this.$parent || this.$root
。没有父母,没有父母是同一回事,因此,如果组件名称不在原始接收者的祖先中,则该函数将永远递归。
在向根搜索树时,实际上有两个终止条件,(1)找到了目标节点,或者(2)到达了根,所以找不到目标节点...
dispatch(componentName,event,value) {
if (this.$options.name === componentName) {
this.$emit(event,value);
} else if (!this.$parent) { // another terminal condition,not found
this.$emit('not found'); // or whatever,just don't recurse here
} else {
return this.dispatch.call(this.$parent,componentName,value);
}
}