How to generate custom tag/element(component) using insertAdjacentHTML in Vue

Using insertAdjacentHTML I can make div, span etc .. html element but cannot make custom tag forexample <myComponent> </myComponent>

Basically insertAdjacentHTML can generate html element, that’s I know but custom Component is also consisted with html tag. So I think there must be a way, generate custom element using like insertAdjacentHTML or else.

I tried test component and basic html element.
what I want is not generate html element but component.

code below is what I tried

“when someone click a button, then generate component” is my purpos

<template>
<button @click="test"></button>
</template>

<script setup>
import multiSelectComp from '@/views/utils/multiSelectComp'
function test(){
let tag = document.getElementById('test3');
  tag.insertAdjacentHTML("afterend", `<multiselect 
        :arg=true>
    </multiselect>`)
}
</script>

  • direct manipulation of the DOM should generally be avoided when using Vue. The framework should manage the DOM for you, and is quite powerful in letting you dynamically edit, insert, remove elements as needed. It’s really an XY problem. What problem is inserting custom components with insertAdjacentHTML solving for you? There is probably a better, Vue-like way to do what you want. Share the code you have and explain what you’re trying to do.

    – 

  • thank you for comment, I add my code and purpose

    – 

  • that can probably be achieved using v-iflike so

    – 




  • Does your code work?

    – 

  • No that code doesn’t work, but I solved the problem with reference the answer below , Also thank you for comment!

    – 

Your code creates a new component on click. Vue can do that in multiple ways.

v-if can be used to only render an element/component if a certain condition is true

v-for can render elements for a given a number of loops.

I’ve coded basic examples of both directives rendering elements in the following Vue Playground

<template>
  <div class="wrapper">
    <button @click="renderOne">click renders single component</button>
    <multiSelectComp v-if="shouldRender"></multiSelectComp>

    <button @click="renderMultiple">multiple click renders multiple component</button>
    <multiSelectComp v-for="i in clicks" :key="i"></multiSelectComp>
  </div>
</template>
<script setup>
import multiSelectComp from './multiSelectComp.vue'
import { ref } from 'vue'

/* strategy 1: single component that is not rendered until condition is true */
const shouldRender = ref(false)
function renderOne(){
  shouldRender.value = true
}

/* strategy 2: render number of components equal to number of clicks */
const clicks = ref(0)
function renderMultiple() {
  clicks.value++
}
</script>

Leave a Comment