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.
Vue 3
In Vue 3, you can check the props on the current component instance for that purpose:
1<script setup lang="ts">
2import { computed, ref, getCurrentInstance } from 'vue';
3
4defineEmits(['click', 'custom-event']);
5
6const hasClickEventListener = computed(
7 () => !!getCurrentInstance()?.vnode.props?.onClick
8);
9const hasCustomEventListener = computed(
10 () => !!getCurrentInstance()?.vnode.props?.['onCustomEvent']
11);
12</script>
Vue 2
In Vue 2, you can use the vm.$listeners
property:
1<script>
2computed:{
3 hasClickEventListener(){
4 return this.$listeners && this.$listeners.click
5 }
6}
7</script>
StackBlitz
Try it yourself in this StackBlitz:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Watch Slot Changes
You can use the MutationObserver API to react to changes in the slot content.
Nuxt Tip: Cancel Fetch API Request
In Nuxt 3, you can use the `signal` parameter with the globally available `$fetch` helper to cancel an API request.