Home > Blockchain >  vue.js: create component from string
vue.js: create component from string

Time:01-03

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

<template>
   <div id="app">
      <input  @keyup="update()">
      <div ></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?

CodePudding user response:

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

<template>
   <div id="app">
      <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

  • Related