繁体   English   中英

vuejs 2.0 中的递归组件通信

[英]recursive component communication in vuejs 2.0

假设组件名称是“customComponent”

及其使用示例:

<custom-component class='parent'>
  <div v-if='someTruthyCondition'>
    <custom-component class='child'></custom-component>
  </div>
</custom-component>

让我们假设,'someTruthyCondition' 是真的 util 3 组件生成和递归停止。

我想知道如何在 vue js 中子 customComponent 与父 customComponent 之间进行通信?

我不确定这是否可行,因为您的示例感觉像代码气味,而且我还没有尝试过这样的事情。 您可以使用事件,并且每当创建子组件时,您都可以向父组件发出事件:

https://v2.vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events

在 Vue.js 文档的示例中,他们使用了这个:

<button-counter v-on:increment="incrementTotal"></button-counter>

所以子组件在created的生命周期钩子中调用它:

this.$emit('increment')

每当您在父母内部收到此事件时,您都可以增加一个数字,当它达到 3 时,您停止您的v-for循环。

<custom-component class='child'></custom-component>

当然,我不知道这是否会奏效,但在我的脑海中,这是我想出的。

您可以在 Vue.js 中将函数用作道具。 这不是一种常见的模式,因为与 React 不同,Vue.js 具有用于子与父通信的自定义事件。 但是对于像这样的情况,它真的派上用场了。

与在每个级别发出事件不同,这更加简单和高效,因为我们只需要传递对函数的相同引用。

看看 这个

我没有对此进行测试,但我认为这样的事情可能会对您有所帮助。

主.js:

window.Event = new Vue();

父元素:

mounted () {
    Event.$on('recursion', () => {
        this.recursion++;
    })
}

子元素:

created () {
    Event.$emit('recursion');
}

使用v-on="$listeners"递归子级触发事件到父级。

当您将任何事件侦听器附加到组件的第一次调用时,您可以通过这种方式附加到所有递归调用组件。

<custom-component class='parent' @click="doSomething()">
  <div v-if='someTruthyCondition'>
    <custom-component class='child' v-on="$listeners"></custom-component>
  </div>
</custom-component>

现在在您使用它的组件中,将有doSomething方法 - 它将被触发到任何递归子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM