We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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>
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.