Home >Web Front-end >Vue.js >How to manually render components to specified elements in Vue3

How to manually render components to specified elements in Vue3

PHPz
PHPzforward
2023-05-21 13:59:182361browse

Convert components to custom elements

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(&#39;my-vue-element&#39;, 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 &#39;vue&#39;
import Example from &#39;./Example.ce.vue&#39;

console.log(Example.styles) // ["/* 内联 css */"]

// 转换为自定义元素构造器
const ExampleElement = defineCustomElement(Example)

// 注册
customElements.define(&#39;my-example&#39;, 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.

Multiple application instances of Vue

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 or reactive, 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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete