[Vuejs]-Cannot dynamically create and add Vue components failed to mount component template or render function not defined

0👍

The problem is that you are instantiating the component and sending that instance to your dynamic component, instead of that you should be registering the component (you are already doing that) and for your dynamic component you need to send only the name of the registered component.

The component registration is happening here:

Vue.component('Condition', require('@/components/Condition.vue').default);

In order to use that component in a dynamic manner you only need to do:

<component :is="'Condition'"/>

as you can see, only the name is needed (as a string) and Vue make the instance of the component.

Here is your code working:

<template>
 <div id="app">
  <v-btn @click="addCondition()" color="secondary" dark>Add Condition</v-btn>
  <div id="conditions">
   <template v-for="condition in conditions">
     <component :is="condition" :key="condition.id"></component>
   </template>
  </div>
 </div>
</template>

<script>
// This component registration only needs to happens once, it could also be in another file
Vue.component("Condition", require("@/components/Condition.vue").default);
import Vue from "vue";

export default {
  name: "Test",
  components: {}, // No need for the component here since you are not using it
  methods: {
    addCondition() {
      // NO need for instances here, nor for Vue.extend because Condition is already a component
      this.conditions.push("Condition");
    },
  },
  data() {
    return {
      conditions: [],
    };
  },
};
</script>

Leave a comment