【发布时间】: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怎么样?在这种情况下,只有color和square由父级传递 -
@Radeanu
<Badge square @onDelete="onDeleteOption(selected_option)">Test</Badge> -
对不起,可以通过
v-if="$listeners.onDelete"这种方式检查是否存在onDelete监听器 -
但是在 Vue 3 中
$listeners被删除了 -
对于 Vue 3 使用
v-if="$attrs.onOnDelete"