vuejs / vue-web-component-wrapper

(Vue 2 only) Wrap a Vue component as a web component / custom element.
1.05k stars 99 forks source link

@vue/web-component-wrapper CircleCI

Wrap and register a Vue component as a custom element.

Compatibility

Requires ES2015 classes. IE11 and below not supported.

Usage

import Vue from 'vue'
import wrap from '@vue/web-component-wrapper'

const Component = {
  // any component options
}

const CustomElement = wrap(Vue, Component)

window.customElements.define('my-element', CustomElement)

It works with async components as well - you can pass an async component factory function that returns a Promise, and the function will only be called when an instance of the custom element is created on the page:

const CustomElement = wrap(Vue, () => import(`MyComponent.vue`))

window.customElements.define('my-element', CustomElement)

Interface Proxying Details

Props

Events

Custom events emitted on the inner Vue component are dispatched on the custom element as a CustomEvent. Additional arguments passed to $emit will be exposed as an Array as event.detail.

Slots

Slots work the same way as expected, including named slots. They also update when changed (using MutationObserver).

Scoped slots however, are not supported as they are a Vue specific concept.

Lifecycle

When the custom element is removed from the document, the Vue component behaves just as if it's inside a <keep-alive> and its deactivated hook will be called. When it's inserted again, the activated hook will be called.

If you wish to destroy the inner component, you'd have to do that explicitly:

myElement.vueComponent.$destroy()

Acknowledgments

Special thanks to the prior work by @karol-f in vue-custom-element.

License

MIT