javascript / expert
Snippet
Custom Web Element Definition with Shadow DOM Attribute Reflection
Vue's `defineCustomElement` converts standard Vue component definitions into native Web Components wrapped in Shadow DOM. Declared props automatically reflect host HTML attributes and custom events dispatch as standard DOM CustomEvents.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { defineCustomElement, h } from 'vue';const CustomBadgeElement = defineCustomElement({props: {variant: { type: String, default: 'info' }},emits: ['badgeClick'],setup(props, { emit }) {return () => h('button', {class: `badge-${props.variant}`,onClick: (e) => emit('badgeClick', e)}, [h('slot')]);}});customElements.define('x-custom-badge', CustomBadgeElement);
vue
Breakdown
1
const CustomBadgeElement = defineCustomElement({
Compiles a Vue component options object into a standard HTMLElement class constructor.
2
onClick: (e) => emit('badgeClick', e)
Dispatches an event from inside the component which bubbles up as a DOM CustomEvent.
3
customElements.define('x-custom-badge', CustomBadgeElement);
Registers the compiled constructor into the browser custom elements registry.