How to listen to custom element events in Vue?

999 views Asked by At

I'm using custom elements (specifically Material Web Components) but I can't figure out how to listen to events from custom elements using the usual v-on syntax.

The following doesn't work:

<mwc-drawer ref='drawer' v-on='{"MDCDrawer:opened": opened}'>

Where as this does:

onMounted(() => {
    drawer.value.addEventListener('MDCDrawer:opened', () => {
        console.log('opened')
    })
})

Does Vue only listen to native events rather than custom ones when it thinks it is a native element (but actually a custom element)?

1

There are 1 answers

1
vangleer On

explain

only when we emit the custom event, we can listen on use. in mwc-drawer.vue we should emit the MDCDrawer:opened event. and then we can use v-on={"MDCDrawer:opened": fn} or @MDCDrawer:opened="fn" listen

official site

demo

  • mwc-drawer.vue
<script setup lang="ts">
import { defineEmits } from 'vue'

const emit = defineEmits(['MDCDrawer:opened'])

function open() {
  // only when we emit the custom event, we can listen on use
  emit('MDCDrawer:opened', { text: 'Hello!!' })
}
</script> 
  • home.vue
<template>
  <mwc-drawer ref='drawer' v-on='{"MDCDrawer:opened": opened}' />
</template>
<script setup lang="ts">
function opened(params) {
  console.log(params) // { text: 'Hello!!' }
}
</script>