为什么在Vue中更改此对象而调用递归方法,抛出错误“ RangeError:超出最大调用堆栈大小” 更新说明代码预期&&详细错误版本尝试

问题描述

更新

添加在线代码笔。.

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);
  }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...