Home >Web Front-end >Vue.js >How to manually render components to specified elements in Vue3
Documentation: Vue and Web Components | Vue.js (vuejs.org)
Vue provides good support for Web Components. Components can be converted into custom elements using defineCustomElement
. You can then freely insert it into the DOM node.
import { defineCustomElement } from 'vue' const MyVueElement = defineCustomElement({ // 这里是同平常一样的 Vue 组件选项 props: {}, emits: {}, template: `...`, // defineCustomElement 特有的:注入进 shadow root 的 CSS styles: [`/* inlined css */`] }) // 注册自定义元素 // 注册之后,所有此页面中的 `<my-vue-element>` 标签 // 都会被升级 customElements.define('my-vue-element', MyVueElement) // 你也可以编程式地实例化元素: // (必须在注册之后) document.body.appendChild( new MyVueElement({ // 初始化 props(可选) }) )
Additionally, it is possible to convert an SFC (Single File Component) into a custom element.
Documentation: sfc as custom element
import { defineCustomElement } from 'vue' import Example from './Example.ce.vue' console.log(Example.styles) // ["/* 内联 css */"] // 转换为自定义元素构造器 const ExampleElement = defineCustomElement(Example) // 注册 customElements.define('my-example', ExampleElement)
It is worth noting that
defineCustomElement
will use Shadow DOM to render the element. This method will cause style isolation, and external styles will not be able to apply to the inside of the component. If you use a component library, or rely on some external styles, remember to import these styles again.
Remember that when creating the project, we used createApp
to create an App
instance, and then It is mounted in #app
. In fact, multiple App instances, that is, multiple Vue applications, can exist in a DOM environment at the same time.
Using this, you can create an App instance again and then mount it on a specific DOM element.
import YouComponent from "./YouComponent.vue"; // 创建一个新的 Vue 应用 const app = createApp(YouComponent); // 将应用挂载到自定义的 DOM 元素上 app.mount("#you-element");
In this way, the component can be rendered normally. The component's provide and inject will be invalid because they do not belong to the original application.
How to communicate between components? You can use custom events, or createEventHook | VueUse. In addition, you can also use the responsiveness principle of Vue3 to create a separate responsive object using
ref
orreactive
, and then reference them in different components to achieve two-way data. Synchronize.
The above is the detailed content of How to manually render components to specified elements in Vue3. For more information, please follow other related articles on the PHP Chinese website!