Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么在Vue中更改this对象时调用递归方法,抛出错误“;RangeError:超过最大调用堆栈大小; 更新_Javascript_Vue.js_This - Fatal编程技术网

Javascript 为什么在Vue中更改this对象时调用递归方法,抛出错误“;RangeError:超过最大调用堆栈大小; 更新

Javascript 为什么在Vue中更改this对象时调用递归方法,抛出错误“;RangeError:超过最大调用堆栈大小; 更新,javascript,vue.js,this,Javascript,Vue.js,This,添加在线代码笔 描述 无法通过调用递归方法调用父方法 代码 预期详细信息错误(&D) dispatch.call(parent)->parent.dispatch.call(parent.parent)->parent.parent.dispatch 详细信息错误: v-on处理程序中出现错误:“RangeError:超出了最大调用堆栈大小” 版本 vue 2.6.1 尝试 它可以工作,我知道原因是dispatch.call(this.$parent)更改了this对象,但是为什么this.d

添加在线代码笔

描述 无法通过调用递归方法调用父方法

代码 预期详细信息错误(&D) dispatch.call(parent)->parent.dispatch.call(parent.parent)->parent.parent.dispatch

详细信息错误: v-on处理程序中出现错误:“RangeError:超出了最大调用堆栈大小”

版本 vue 2.6.1

尝试
它可以工作,我知道原因是dispatch.call(this.$parent)更改了this对象,但是为什么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, event, value);
  }
}

谢谢,这是我已经修复的另一个问题,但是发布的问题仍然存在,
function dispatch(componentName, event, value) {
  if (this.$options.name === componentName) {
    this.$emit(event, value);
  } else {
    const parent = this.$parent || this.$root;
    return dispatch.call(parent, componentName, event, value);
  }
}
export default {
  methods: {
    dispatch(componentName, event, value) {
      dispatch.call(this, componentName, event, value);
    }

    // broadcast(componentName, event, value) {}
  }
};

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, event, value);
  }
}