131 words, 1 min read

Sometimes, you want to apply specific styles to a component only if it has an event listener attached. For example, you might want to add a cursor: pointer style to a component only if it has a click event listener attached.

In Vue 3, you can check the props on the current component instance for that purpose:

The child component can look like this:

<script setup lang="ts">
import { computed, ref, getCurrentInstance } from 'vue';
defineEmits(['click', 'custom-event']);
const hasClickEventListener = computed(
() => !!getCurrentInstance()?.vnode.props?.onClick
);
const hasCustomEventListener = computed(
() => !!getCurrentInstance()?.vnode.props?.['onCustomEvent']
);
</script>

The parent component can look like this:

<script setup lang="ts">
import Child from './components/Child.vue';
const onClick = () => console.log('Click');
const onCustomEvent = () => console.log('Custom event');
</script>
<template>
<Child />
<Child @click="onClick" @custom-event="onCustomEvent" />
</template>

source