search

Home  >  Q&A  >  body text

Best Practice: How to attach components to the DOM in Vue 3

<p>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 <code><script setup></code> style component and that's another problem. </p> <p>This seems unnecessarily difficult. </p> <p>Here's roughly what I want to do:</p> <ol> <li>Get some data. Has been completed. </li> <li>Create an instance of the Vue component: Foo.vue. </li> <li>Pass data to it as properties. </li> <li>Append it where I want it. </li> </ol> <p>The problem is, I can't use <component :is="Foo:> in the template because I don't know where it will be long after the template is rendered.</p> <p>Are there any best practices? Is there any kind person who can provide a simple example, I would be very grateful. </p> <p>I sometimes can't understand the Vue documentation half the time. Sorry, hate to say it, but for a newbie to Vue, they are quite obscure and make me feel stupid. </p> <p>Here's some fake code for what I'm trying to do: </p> <pre class="brush:php;toolbar:false;">import Foo from "../components/Foo.vue" function makeAFoo(p, data){ // Instantiate my Foo.vue (not sure how to do this inline) and pass it the required data let foo = new Foo(data); // If only it were that simple, right? //Append it to p (which is an HTML element) p.appendChild(foo) }</pre> <p><br /></p>
P粉362071992P粉362071992451 days ago590

reply all(2)I'll reply

  • P粉004287665

    P粉0042876652023-08-25 18:25:26

    An easier way is to use v-if or v-for.

    Instead of dealing with the component directly, it is better to deal with the state of the component and let Vue's responsive magic work

    This is an example, dynamically add a component (Toast), just operate the state of the component

    Toast.vue file: The v-for here is reactive, whenever a new error is added to the errors object, it will be rendered

    <script setup lang="ts">
    import { watch } from 'vue';
    import { ref, onUpdated } from 'vue';
    import { Toast } from 'bootstrap';
    
    const props = defineProps({
      errors: { type: Array, default: () => [] },
    });
    
    onUpdated(() => {
      const hiddenToasts = props.errors.filter((obj) => {
        return obj.show != true;
      });
      hiddenToasts.forEach(function (error) {
        var errorToast = document.getElementById(error.id);
        var toast = new Toast(errorToast);
        toast.show();
        error.show = true;
        errorToast.addEventListener('hidden.bs.toast', function () {
          const indexOfObject = props.errors.findIndex((item) => {
            return item.id === error.id;
          });
          if (indexOfObject !== -1) {
            props.errors.splice(indexOfObject, 1);
          }
        });
      });
    });
    </script>
    <script lang="ts">
    const TOASTS_MAX = 5;
    export function push(array: Array, data): Array {
      if (array.length == TOASTS_MAX) {
        array.shift();
        array.push(data);
      } else {
        array.push(data);
      }
    }
    </script>
    
    <template>
      <div
        ref="container"
        class="position-fixed bottom-0 end-0 p-3"
        style="z-index: 11"
      >
        <div
          v-for="item in errors"
          v-bind:id="item.id"
          class="toast fade opacity-75 bg-danger"
          role="alert"
          aria-live="assertive"
          aria-atomic="true"
          data-bs-delay="15000"
        >
          <div class="toast-header bg-danger">
            <strong class="me-auto text-white">Error</strong>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="toast"
              aria-label="Close"
            ></button>
          </div>
          <div class="toast-body text-white error-body">{{ item.msg }}</div>
        </div>
      </div>
    </template>
    

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

    <script setup lang="ts">
    import { ref, reactive } from 'vue';
    import toast from './Toast.vue';
    import { push } from './Toast.vue';
    
    const count = ref(0);
    const state = reactive({ errors: [] });
    
    function pushError(id: int) {
      push(state.errors, { id: id, msg: 'Error message ' + id });
    }
    </script>
    
    <template>
      <toast :errors="state.errors"></toast>
    
      <button type="button" @click="pushError('toast' + count++)">
        Error trigger: {{ count }}
      </button>
    </template>

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

    reply
    0
  • P粉598140294

    P粉5981402942023-08-25 00:33:13

    Option 1: Use createVNode(component, props) and render(vnode, container)

    Create: Use createVNode() to create a component-defined VNode with props (for example, from *.vue imported SFC), which can be passed to render() to render on the given container element.

    Destruction: Calling render(null, container) will destroy the VNode attached to the container. This method should be called to clean up when the parent component is unmounted (via the unmounted lifecycle 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 (createVNode and render), which may be refactored or removed in future versions.

    Demo 1

    Option 2: Use createApp(component, props) and app.mount(container)

    Create: Use createApp() to create an application instance. This instance has a mount() method that can be used to render the component on a given container element.

    Destruction: Application instances have unmount() methods to destroy application and component instances. This method should be called to clean up when the parent component is unmounted (via the unmounted lifecycle 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

    <script setup>
    import { ref, onUnmounted, getCurrentInstance } from 'vue'
    import renderComponent from './renderComponent'
    
    const { appContext } = getCurrentInstance()
    const container = ref()
    let counter = 1
    let destroyComp = null
    
    onUnmounted(() => destroyComp?.())
    
    const insert = async () => {
      destroyComp?.()
      destroyComp = renderComponent({
        el: container.value,
        component: (await import('@/components/HelloWorld.vue')).default
        props: {
          key: counter,
          msg: 'Message ' + counter++,
        },
        appContext,
      })
    }
    </script>
    
    <template>
      <button @click="insert">插入组件</button>
      <div ref="container"></div>
    </template>
    

    reply
    0
  • Cancelreply