【问题标题】:Vue3: Check if event listener is bound to component instanceVue3:检查事件监听器是否绑定到组件实例
【发布时间】:2022-01-13 05:55:16
【问题描述】:

我有一个可重复使用的徽章组件。当组件实例上存在 onDelete 事件侦听器时,我希望能够添加关闭/删除按钮。

<template>
    <div class="flex inline-flex items-center px-2.5 py-0.5 text-xs font-medium select-none" :class="[square ? '' : 'rounded-full']">
        <slot />
        <button class="cursor-pointer ml-2" @click="$emit('onDelete')">
            <XIcon class="flex-shrink-0 h-3.5 w-3.5 text-gray-400 hover:text-gray-500" aria-hidden="true" />
        </button>
    </div>
</template>

<script>
    import { XIcon } from '@heroicons/vue/solid';

    export default {
        props: {
            color: { type: String },
            square: { type: Boolean, default: false },
        },
        components: {
            XIcon,
        },
        emits: ['onDelete'],
    };
</script>

如果我在按钮上添加 v-if 语句,则立即执行 emit 事件

<button v-if="$emit('onDelete')" class="cursor-pointer ml-2" @click="$emit('onDelete')">

我正在使用 Vue 3

【问题讨论】:

  • onDelete emit is passed by the parent component 怎么样?在这种情况下,只有 colorsquare 由父级传递
  • @Radeanu &lt;Badge square @onDelete="onDeleteOption(selected_option)"&gt;Test&lt;/Badge&gt;
  • 对不起,可以通过v-if="$listeners.onDelete"这种方式检查是否存在onDelete监听器
  • 但是在 Vue 3 中 $listeners 被删除了
  • 对于 Vue 3 使用 v-if="$attrs.onOnDelete"

标签: vue.js vuejs3


【解决方案1】:

更新:如果您的组件在 Vue3 中使用新的 emits option,这是 Vue3 文档中推荐的最佳实践,则事件侦听器将不会与 $attrs 分开。将向 Vue 团队提交一个问题,以澄清和指导这种行为的原因。


我在 StackBlitz 中简化了您上面的示例,以隔离您所追求的功能。

重要提示,我使用的是 Vue 3.2.26。

在 Vue3 中 $listeners were removed.

事件监听器现在是$attrs 的一部分。但是,在Badge 中简单地控制台记录this.$attrs 不会显示您要查找的密钥,它们在targets 内,但可以通过在绑定事件名称前添加on 来访问。在Badge 组件中,您将使用onOnDelete

带有两个徽章的完整工作示例。一个会显示,因为它有一个绑定事件onDelete,另一个不会显示,因为绑定的onDelete 不存在。

https://stackblitz.com/edit/vue-8b6exq?devtoolsheight=33&file=src/components/Badge.vue

【讨论】:

  • 该示例正在运行,但在我的项目中不起作用。问题是脚本标签中的emits: ['onDelete']。添加时v-if="$attrs.onOnDelete" 不起作用。没有它的工作
  • @Thore 非常有趣。我刚刚验证了这一点。您可能需要考虑将此问题报告给 Vue 团队
猜你喜欢
  • 1970-01-01
  • 2011-06-01
  • 2018-08-14
  • 1970-01-01
  • 2018-03-24
  • 2017-11-29
  • 1970-01-01
  • 2017-02-25
  • 2021-06-24
相关资源
最近更新 更多