Javascript is required
·
1 min read

Vue Tip: Check if Component Has Event Listener Attached

Vue Tip: Check if Component Has Event Listener Attached Image

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>
1<script setup lang="ts">
2import Child from './components/Child.vue';
3
4const onClick = () => console.log('Click');
5const onCustomEvent = () => console.log('Custom event');
6</script>
7
8<template>
9  <Child />
10  <Child @click="onClick" @custom-event="onCustomEvent" />
11</template>

Vue 2

In Vue 2, you can use the vm.$listeners property:

Component.vue
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:

I will never share any of your personal data. You can unsubscribe at any time.