Dickson Afful
Dickson Afful

Reputation: 838

How to create component and mount dynamically in vuejs

Is there a way to create and mount components in a template dynamically. I attempted it but did not work. Below is the code. I have commented on the code on how I had wanted to achieve this.

<template>
  <v-container>
    <v-row>
      <v-col cols="12" sm="12" class="d-flex flex-row">
        <v-btn color="success" @click="addField">Add Field</v-btn>
      </v-col>
      <v-col cols="12" sm="12" id="container">
        mounts components here
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Vue from "vue";

export default {
  methods: {
    addField() {
      //creates component
      let newComponent = Vue.component("some-component", {
        data() {
          return {
            name: "John"
          };
        },
        template: "<template><p>{{name}}</p></template>"
      });
      //insert component in template
      newComponent.$mount("#container");
    }
  }
};
</script>

Upvotes: 1

Views: 1280

Answers (3)

fabtrons
fabtrons

Reputation: 69

You can dynamically control component by implementing this code below, you can manipulate the switchComponent function with vuejs events or providers as you wish.

<script setup>
import { shallowRef } from "vue";
import ComponentA from "../components/ComponentA.vue";
import ComponentB from "../components/ComponentB.vue";

let currentComponent = shallowRef(ComponentA);

/**
 * registered components
 */
let components = {
  ComponentA: ComponentA,
  ComponentB: ComponentB,
};

const switchComponent = (component) => {
  currentComponent.value = components[component];
};

</script>

<template>
  <component :is="currentComponent"></component>
</template>

Upvotes: 0

Reinier68
Reinier68

Reputation: 3272

Yes. You can use <component is="nameOfYourComponent"/> to load components dynamically. See here a very simple example in a codesandbox

And of course, the docs: https://v2.vuejs.org/v2/guide/components-dynamic-async.html

Upvotes: 2

David ROSEY
David ROSEY

Reputation: 1805

I don't cleary understand the usecase tou want to achieve.

However, maybe you can get what you want using Slots (https://v2.vuejs.org/v2/guide/components-slots.html) or Dynamic & Async Components (https://v2.vuejs.org/v2/guide/components-dynamic-async.html)

Upvotes: -1

Related Questions