Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js: create component from string

I have two components named component-1 and component-2, along with this vue.js code:

<template>
   <div id="app">
      <input class="input" @keyup="update()">
      <div class="render"></div>
   </div>
</template>

<script>
export default {
   methods:{
      update () {
         document.querySelector(".render").innerHTML=`<component-${
            document.querySelector(".input").value
         } />`
      }
   }
}
</script>

Whenever I run the code, the component doesn't render. Is there a way to get this component to render?

like image 959
codingtuba Avatar asked Dec 06 '25 02:12

codingtuba


1 Answers

This isn't the right way to render components dynamically in Vue - instead you should use :is

<template>
   <div id="app">
      <input class="input" @keyup="update($event.target.value)">
      <component :is="myComponent"></component>
      </div>
</template>

<script>
export default {
   data() {
     return {
       myComponent: undefined
     }
   },
   methods:{
      update (component) {
         this.myComponent = component
      }
   }
}
</script>

A sandbox demo is here

like image 111
match Avatar answered Dec 07 '25 17:12

match