Vue3 - 将多个事件侦听器及其处理程序传递给子组件

PHi*_*rth 4 javascript vue.js vue-component vuejs3

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

父组件:

<ChildComponent :props="{ id: 'the-id', class: 'the-class' }" />
Run Code Online (Sandbox Code Playgroud)

子组件:

<ChildComponent :props="{ id: 'the-id', class: 'the-class' }" />
Run Code Online (Sandbox Code Playgroud)

这将导致 HTML 如下所示:

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

<script>
export default {
    props: {
        props: { type: Object }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

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

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

是否可以做类似的事情?

父组件:

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

子组件:

<input id="the-id" class="the-class" />
Run Code Online (Sandbox Code Playgroud)

谢谢 ;)

Tho*_*mas 6

您还可以通过将对象传递给以下内容来执行与处理 props 类似的操作v-on

<input v-on="{ input: doThis, blur: doThat }"></button>
Run Code Online (Sandbox Code Playgroud)

请参阅此处: https: //v3.vuejs.org/api/directives.html#v-on