Best Practice: How to attach components to the DOM in Vue 3
P粉362071992
P粉362071992 2023-08-24 19:51:03
0
2
539

I want to dynamically create a component in my Vue 3 application, inside a Single File Component (SFC), and append it to the DOM. I'm using a

ErrorTrigger.vue: Whenever a click event occurs, we push an error to the errors object

 

Full example:https://stackblitz.com/edit/vitejs-vite-mcjgkl

    P粉598140294

    Option 1: UsecreateVNode(component, props)andrender(vnode, container)

    Create:UsecreateVNode()to create a component-definedVNodewith props (for example, from*.vueimported SFC), which can be passed torender()to render on the given container element.

    Destruction:Callingrender(null, container)will destroy theVNodeattached to the container. This method should be called to clean up when the parent component is unmounted (via theunmountedlifecycle hook).

    // renderComponent.js import { createVNode, render } from 'vue' export default function renderComponent({ el, component, props, appContext }) { let vnode = createVNode(component, props) vnode.appContext = { ...appContext } render(vnode, el) return () => { // destroy vnode render(null, el) vnode = undefined } }

    Note:This method relies on internal methods (createVNodeandrender), which may be refactored or removed in future versions.

    Demo 1

    Option 2: UsecreateApp(component, props)andapp.mount(container)

    Create:UsecreateApp()to create anapplication instance. This instance has amount()method that can be used to render the component on a given container element.

    Destruction:Application instances haveunmount()methods to destroy application and component instances. This method should be called to clean up when the parent component is unmounted (via theunmountedlifecycle hook).

    // renderComponent.js import { createApp } from 'vue' export default function renderComponent({ el, component, props, appContext }) { let app = createApp(component, props) Object.assign(app._context, appContext) // 必须使用Object.assign在_context上 app.mount(el) return () => { // 销毁app/component app?.unmount() app = undefined } }

    Note:This method creates an application instance for each component. If multiple components need to be instantiated in the document at the same time, it may cause considerable overhead.

    Demo 2

    Example usage

     
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!