【问题标题】:Vue3 - pass multiple event listeners along with their handlers to child componentVue3 - 将多个事件侦听器及其处理程序传递给子组件
【发布时间】:2021-11-16 05:56:49
【问题描述】:

在 Vue3 中,我可以执行以下操作:

父组件:

<ChildComponent :props="{ id: 'the-id', class: 'the-class' }" />

子组件:

<template>
    <input v-bind="props" />
</template>

<script>
export default {
    props: {
        props: { type: Object }
    }
}
</script>

这将导致 HTML 如下所示:

<input id="the-id" class="the-class" />

我仍在学习 Vue,我想知道是否可以对事件侦听器/处理程序做同样的事情。

对于可重用组件,我可能需要不同的事件侦听器/处理程序,具体取决于我使用组件的位置。在一种形式中,我可能只需要子组件中的@input="...",在另一种形式中,我可能还需要@blur="...",或者我可能根本不需要事件监听器。

可以做类似的事情吗?

父组件:

<ChildComponent :events="{ input: function() { alert('input!'); }, blur: function() { alert('blur!'); } } />

子组件:

<template>
    <input @events />
</template>

<script>
export default {
    props: {
        props: { type: Object }
    }
}
</script>

谢谢;)

【问题讨论】:

标签: javascript vue.js vue-component vuejs3


【解决方案1】:

我的建议是通过 Vue 的自定义事件定义不同的事件;自定义事件将允许组件的用户选择订阅哪个事件并相应地处理它。

https://vuejs.org/v2/guide/components-custom-events.html

【讨论】:

    【解决方案2】:

    组件的根元素automatically inherits all non-prop attributes(包括事件监听器)从父组件应用到组件。因此,如果&lt;input&gt; 真的是ChildComponent 的根,则无需声明任何内容,只需将属性应用于ChildComponent,就好像它是input 本身一样:

    <ChildComponent id="the-id" class="the-class" @blur="onBlur" />
    

    demo 1

    但是,一旦您将另一个元素添加到 ChildComponent,这将中断,因为 &lt;input&gt; 将不再是根。如果您想切换根元素(例如,包装&lt;input&gt;&lt;label&gt;),这也是一个问题。

    disable automatic attribute inheritance,允许控制应用继承属性的位置,在组件选项中设置inheritAttrs: false。 (当有多个根节点时不需要禁用它,因为它只适用于单根组件。)然后手动将v-bind $attrs prop 到其中的任何元素:

    <template>
      <label>My input: <input v-bind="$attrs"></label>
    </template>
    
    <script>
    export default {
      inheritAttrs: false,
    }
    </script>
    

    demo 2

    【讨论】:

      【解决方案3】:

      你也可以像处理 props 一样做类似的事情,将对象传递给v-on

      <input v-on="{ input: doThis, blur: doThat }"></button>
      

      请看这里:https://v3.vuejs.org/api/directives.html#v-on

      【讨论】:

        猜你喜欢
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-16
        • 2010-09-12
        • 1970-01-01
        相关资源
        最近更新 更多