vuejs / core

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
https://vuejs.org/
MIT License
47.68k stars 8.33k forks source link

defineCustomElement does not support async component #4261

Closed gnuletik closed 3 years ago

gnuletik commented 3 years ago

What problem does this feature solve?

While the new defineCustomElement feature is really nice, it does not supports async components.
This feature is useful when you want to define multiple web components in one file without loading all of them (they will be loaded when the custom elements are used).

The following attempt mount the component but custom elements attributes are not passed to the Vue component.

customElements.define(
  'my-element',
  defineCustomElement(defineAsyncComponent(() => import('MyComponent.vue')))
)

Async components are currently supported by web-component-wrapper for Vue 2.x (https://github.com/vuejs/vue-web-component-wrapper)

const CustomElement = wrap(Vue, () => import(`MyComponent.vue`))
window.customElements.define('my-element', CustomElement)

What does the proposed API look like?

The defineCustomElement function could receive a function returning a Promise to a Vue Component like this :

customElements.define(
  'my-element',
  defineCustomElement(() => import('MyComponent.vue'))
)

When the <my-element></my-element> element is inserted somewhere in the DOM, the MyComponent.vue file should be be downloaded by the browser (if not already) and mounted.

yyx990803 commented 3 years ago

A note: when importing SFCs as custom elements, the tooling needs to process the SFC styles as inlined CSS strings for shadow DOM injection.

This use case makes me realize that the current way SFC toolings handle custom elements (which imports the SFC directly as the custom element constructor) is flawed, since it makes it impossible to define a custom element with defineAsyncComponent + SFC. So I'll have to rework the behavior in @vitejs/plugin-vue and vue-loader.

gnuletik commented 3 years ago

Awesome ! Thanks for the super fast fix @yyx990803 and congrats for the 3.2 release !