·
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:

<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>
<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>

Vue 2

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

Component.vue
<script> computed:{ hasClickEventListener(){ return this.$listeners && this.$listeners.click } } </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.