Skip to content

Commit 7fe57bf

Browse files
committed
update sfc custom element usage
1 parent 8614424 commit 7fe57bf

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/guide/web-components.md

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,21 +165,28 @@ The [Provide / Inject API](/guide/component-provide-inject.html#provide-inject)
165165

166166
### SFC as Custom Element
167167

168-
The official build toolchains have built-in support for importing Vue Single File Components (SFCs) as custom elements. By default, files ending in `*.ce.vue` will be processed as native custom elements when imported (created with `defineCustomElement`):
168+
`defineCustomElement` also works with Vue Single File Components (SFCs). However, with the default tooling setup, the `<style>` inside the SFCs will still be extracted and merged into a single CSS file during production build. When using an SFC as a custom element, it is often desirable to inject the `<style>` tags into the custom element's shadow root instead.
169+
170+
The official SFC toolings support importing SFCs in "custom element mode" (requires `@vitejs/plugin-vue@^1.4.0` or `vue-loader@^16.5.0`). An SFC loaded in custom element mode inlines its `<style>` tags as strings of CSS and exposes them under the component's `styles` option. This will be picked up by `defineCustomElement` and injected into the element's shadow root when instantiated.
171+
172+
To opt-in to this mode, simply end your component file name with `.ce.vue`:
169173

170174
```js
175+
import { defineCustomElement } from 'vue'
171176
import Example from './Example.ce.vue'
172177

173-
// register
174-
customElements.define('my-example', Example)
178+
console.log(Example.styles) // ["/* inlined css */"]
175179

176-
// can also be instantiated
177-
const myExample = new Example()
180+
// convert into custom element constructor
181+
const ExampleElement = defineCustomElement(Example)
182+
183+
// register
184+
customElements.define('my-example', ExampleElement)
178185
```
179186

180-
When imported as custom elements, `<style>` inside the SFC will be inlined as JavaScript strings and inserted as a native `<style>` tag inside the custom element's shadow root.
181187

182-
If you wish to customize what files should be imported as custom elements (for example treating _all_ SFCs as custom elements), you can pass the `customElement` option to the respective build plugins:
188+
189+
If you wish to customize what files should be imported in custom element mode (for example treating _all_ SFCs as custom elements), you can pass the `customElement` option to the respective build plugins:
183190

184191
- [@vitejs/plugin-vue](https://github.com/vitejs/vite/tree/main/packages/plugin-vue#using-vue-sfcs-as-custom-elements)
185192
- [vue-loader](https://github.com/vuejs/vue-loader/tree/next#v16-only-options)

0 commit comments

Comments
 (0)