Here's how to do with createApp in Vue 3, but the context (stores, plugins, directives...) will not be kept.

Copy// DialogService.js
import { createApp } from 'vue';

export default {
  alert(text) {
    const mountEl = document.createElement('div');
    document.body.appendChild(mountEl);

    const dialog = createApp({ extends: DialogComponentDef }, {
      // props
      text,
      // events are passed as props here with on[EventName]
      onClose() {
        mountEl.parentNode.removeChild(mountEl);
        dialog.unmount();
        dialog = null;
      },
    });

    dialog.mount(mountEl);
  },
};

To keep the context, there's something more complicated that can be seen here with h and render Vue methods : https://github.com/vuejs/vue-next/issues/2097#issuecomment-709860132

Answer from darkylmnx on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Frameworks_libraries › Vue_first_component
Creating our first Vue component - Learn web development | MDN
June 23, 2025 - For this component, we'll use the object registration method. Go back to your ToDoItem.vue file. Add a props property inside the export default {} object, which contains an empty object. Inside this object, add two properties with the keys label and done. The label key's value should be an ...
Discussions

vue.js - vue2 - Programmatically create component and slots - Stack Overflow
When creating vue (2.17.4) components programmatically, it does not take data from the domnode. If you use new Vue() it does. For components created using Vue.component or Vue.extend, the props and More on stackoverflow.com
🌐 stackoverflow.com
Creating components programmatically?
I think you want dynamic components? computed: { processedHtml() { let html = this.your.propstring; const regexp = /\B#\S+\b/g const matches = html.matchAll(regexp) for (const match of matches) { if (match[0]) { html = html.replace(match[0], '') } } } } The formatting is a little messed up, but basically put your prop into a computed property, there you can generate the component you need. Then use the component in your template. More on reddit.com
🌐 r/vuejs
11
1
December 21, 2022
How to programmatically create Vue Components indirectly
I'm attempting to add components programatically to a page in my Vue Single file Component which works beautifully if you know what you'd like to do ahead of time. In my case, the components and th... More on stackoverflow.com
🌐 stackoverflow.com
Programatically create and mount a component instance
What problem does this feature solve? With vue 2.x, the Vue.component() method did return a component constructor that could be used to programatically create an instance of that component: const M... More on github.com
🌐 github.com
7
August 6, 2020
🌐
CSS-Tricks
css-tricks.com › creating-vue-js-component-instances-programmatically
Creating Vue.js Component Instances Programmatically | CSS-Tricks
January 23, 2018 - But if you notice carefully the script block in any of the above component code, they are all exporting a simple object, and not a class (constructor function). If I do this: import Button from 'Button.vue' var instance = new Button()
🌐
Stack Overflow
stackoverflow.com › questions › 75757648 › vue2-programmatically-create-component-and-slots
vue.js - vue2 - Programmatically create component and slots - Stack Overflow
const Test = Vue.component('Test',{ name: 'Test', props: ['prop'], template: `<div class="hello"> SLOTCONTENT: <slot name="name">default from template</slot><br> PROPS: {{$props}} </div>` }); new Vue({el:'#el1'}) new Test({el:'#el2'}) new Test({el:'#el3', propsData:{prop:'el3prop from propsdata'}}) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.14/vue.min.js"></script> Component created with new Vue() <Test id="el1" prop="el1prop"> <template #name>el1 (from markup)</template> </Test> <br><br> Component created with new Test() <Test id="el2" prop="el2prop"> <template #name>el2 (from markup)</template> </Test> <br><br> Component created with new Test() propsData supplied <Test id="el3" prop="el3prop"> <template #name>el3 (from markup)</template> </Test>
🌐
Reddit
reddit.com › r/vuejs › creating components programmatically?
r/vuejs on Reddit: Creating components programmatically?
December 21, 2022 -

I use Vue3 with Vite.

I have a dozen of components, all defined as SFCs and using the composition API and the script setup syntax. They all look pretty similar to this:

<template>
    <p>My component</p>
</template>
<script setup>
    const props = defineProps({
        propA: {
            type: String,
            default: ''
        }
    });
</script>

I am trying to create instances of these components, and add them to my app, programmatically. And so far, all the methods I have read about online, fail miserably.

The most promising seem to be the one described in this comment in an issue of the official Vue GitHub. Here is how I implemented it:

var myComponentInstance = defineComponent({
    extends: myComponent,
    data: () => ({
        props: {
            propA: 'ABCDE'
        }
    })
});
createApp(TitleComponent).mount(this.$refs.container);

But even though I think I'm doing what's expected, it fails miserably and I get tons of JS errors.

Is there an easy way to create instances of various Components (providing data via props) and mount them in my app, reliably?


I figured how to do it using <component :is="type" /> and wrote this exemple.

Top answer
1 of 2
4

It turns out that Vue has <component :is="yourComponentType"> which does exactly what I was hoping to accomplish if you throw it into a v-for loop. Documents here.

2 of 2
2

You can use Async components to retrieve a component via an API.

I've tested with GraphQL via Axios but it should work with any REST service.

The main component looks like that:

<template>
  <div>
    <h1>Test page</h1>
    <div><button @click="clicked = true">Load component</button></div>
    <async-component v-if="clicked" />
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      clicked: false,
    };
  },
  components: {
    'async-component': () => axios.post('http://localhost:5000/graphql', { query: `
      {
        asyncComponentByRowId(rowId: 1) {
          component
          content
        }
      }
    `,
    }).then((response) => {
      const comp = response.data.data.asyncComponentByRowId.content;
      // eval can be harmful
      return eval(`(${comp})`);
    }),
  },
};
</script>

The retrieved component is in the following format:

{
  "data": {
    "asyncComponentByRowId": {
      "component": "my-async-component",
      "content": "{\r\n\ttemplate: '<div>{{ msg }}</div>',\r\n\tdata: function() {\r\n\t\treturn {\r\n\t\t\tmsg: 'Async component works!'\r\n\t\t};\r\n\t}\r\n}"
    }
  }
}

The decoded data.asyncComponentByRowId.content property is a string representing a JavaScript object:

{
  template: '<div>{{ msg }}</div>',
  data: function() {
    return {
      msg: 'Async component works!'
    };
  }
}

When the button is pressed, the component is shown after being downloaded from the API asynchronously.

The only problem is that I'm using eval to decode the object.

Result:

🌐
GitHub
github.com › vuejs › core › issues › 1802
Programatically create and mount a component instance · Issue #1802 · vuejs/core
August 6, 2020 - const app = Vue.createApp({}); const MyComponent = app.component('my-component', { template: '<div>Hello {{name}}</div>', props: ['name'] }); const myComponent = new MyComponent({ propsData: { name: 'Thomas' } }); myComponent.$mount('#my-co...
Author   mofux
Find elsewhere
🌐
Devshive
devshive.tech › link › bjuzubxle › creating-vuejs-component-instances-programmatically
Creating Vue.js Component Instances Programmatically | Devs' Hive
February 24, 2019 - ... ...it fails. We need a class. Or, in simple terms, a constructor function. The way to do that is to pass the component object to Vue.extend to create a subclass of the Vue constructor.
🌐
Vue.js
vuejs.org › guide › essentials › component-basics
Components Basics | Vue.js
You can also use the is attribute to create regular HTML elements. When switching between multiple components with <component :is="...">, a component will be unmounted when it is switched away from. We can force the inactive components to stay "alive" with the built-in <KeepAlive> component. If you are writing your Vue templates directly in the DOM, Vue will have to retrieve the template string from the DOM.
🌐
GitHub
github.com › vuejs › rfcs › discussions › 582
Improve rendering vue components programmatically · vuejs/rfcs · Discussion #582
Render and mount a vue component inside a specific dom element programmatically. Easly update its props and propely utilize vue's diffing algorithm to update the mounted component template.
Author   vuejs
Top answer
1 of 4
12

1) Since you're manually instantiating that component and it doesn't belong to your main app's component tree, the store won't be automatically injected into it from your root component. You'll have to manually provide the store to the constructor when you instantiate the component ..

import ProjectRow from "./ProjectRow.vue";
import Vue from "vue";
import store from "../store";

let ProjectRowClass = Vue.extend(ProjectRow);
let ProjectRowInstance = new ProjectRowClass({ store });

2) In a Vue Single File Component (SFC), outside of the default export this doesn't refer to the Vue instance, so you don't have access to $refs or any other Vue instance property/method. To gain access to the Vue instance you'll need to move this line this.$refs.container.appendChild(instance.$el) somewhere inside the default export, for example in the mounted hook or inside one of your methods.

See this CodeSandbox for an example of how you may go about this.

2 of 4
2

This is another way to instantiate a component in Vue.js, you can use two different root elements.

// Instantiate you main app
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

//
// Then instantiate your component dynamically
//

// Create a component or import it.
const Hello = {
  props: ['text'],
  template: '<div class="hello">{{ text }}</div>',
};

// Create a componentClass by Vue.
const HelloCtor = Vue.extend(Hello);

// Use componentClass to instantiate your component.
const vm = new HelloCtor({
  propsData: {
    text: 'HI :)'
  }
})
// then mount it to an element.
.$mount('#mount');


🌐
Vue.js
v2.vuejs.org › v2 › guide › components-dynamic-async
Dynamic & Async Components — Vue.js
That’s because each time you switch to a new tab, Vue creates a new instance of the currentTabComponent. Recreating dynamic components is normally useful behavior, but in this case, we’d really like those tab component instances to be cached once they’re created for the first time. To solve this problem, we can wrap our dynamic component with a <keep-alive> element: ... Now the Posts tab maintains its state (the selected post) even when it’s not rendered. See this example for the complete code.
🌐
GitHub
github.com › vuejs › core › issues › 2331
Vue3 Creating Component Instances Programmatically · Issue #2331 · vuejs/core
October 7, 2020 - import Button from 'Button.vue' import Vue from 'vue' var ComponentClass = Vue.extend(Button) var instance = new ComponentClass() instance.$mount() // pass nothing this.$refs.container.appendChild(instance.$el) extend create instance. But in vue3 it's has been deleted. Where are another way? Like vue2 · 👍React with 👍4adamberecz, Calvin-2DWeb, anafro and arthabus ·
Author   art2limit
🌐
Stack Overflow
stackoverflow.com › questions › 40933380 › vue-js-create-component-programmatically
Vue js create component programmatically
December 2, 2016 - Therefore you'd set the modal component within the root of your app, as you say before the body tag: <div id="app"> ... <modal v-if"showModal" inline-template> <div v-html="modalContent"></div> </modal> </div> </body> Now create a vuex store which will allow you to toggle the modal along with I assume populating it's content: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) new Vuex.Store({ state: { showModal: false, modalContent: '', }, mutations: { toggleModal: (state) => { state.showModal = !state.showModal }, setModalContent: (state, content) => { state.modalContent = content }, }, })
🌐
Vue.js
v2.vuejs.org › v2 › guide › components
Components Basics — Vue.js
Fortunately, this task is made very simple by Vue’s custom <slot> element: As you’ll see above, we just add the slot where we want it to go – and that’s it. We’re done! That’s all you need to know about slots for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Slots. Sometimes, it’s useful to dynamically switch between components, like in a tabbed interface: ... See this example to experiment with the full code, or this version for an example binding to a component’s options object, instead of its registered name.
🌐
DEV Community
dev.to › pikax › dynamic-components-using-vuejs-4b78
Dynamic components using VueJS - DEV Community
July 26, 2019 - Passionate about new tech. VueJS lover <3 ... If you have a component definition, you can have a component that loads the component from the API, I would use eval to run the javascript (using the same logic as in On-the-fly components Example).
🌐
Stack Overflow
stackoverflow.com › questions › 59870092 › how-to-generate-vue-components-from-javascript
vue.js - How to generate Vue components from Javascript - Stack Overflow
perhaps you need to read how Vue works again - there's probably a better (in terms of how Vue works) way to do what you are attempting to achieve ... You can also add all your components into html like now but add v-if="type=='FreeText'" and show only correct component by question type. ... Also you can use v-bind:is like this example jsfiddle.net/chrisvfritz/o3nycadu from vue docs "dynamic components"
🌐
Telerik
telerik.com › blogs › dynamic-components-vue-component
Dynamic Components with Vue's 'component'
November 30, 2020 - In this article we will explore Vue's , , and how to create dynamically loaded components.