import {defineComponent,createApp} from 'vue'

buttonView = defineComponent({
    extends: Button, data() {
        return {
            type: "1111"
        }
    }
})

const div = document.createElement('div');
this.$refs.container.appendChild(div);
createApp(buttonView ).mount(div)
Answer from Max on Stack Overflow
🌐
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.

🌐
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)
Author   art2limit
🌐
Reddit
reddit.com › r/vuejs › vue3 - how to create component instances programmatically?
r/vuejs on Reddit: Vue3 - How to create component instances programmatically?
August 23, 2020 -

I'm porting some old code that is basically this:

import Modal from 'Modal.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Modal)
var instance = new ComponentClass({
    propsData: { title: 'title' }
})
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

I can't seem to find a way to get this working using Vue3.
Vue.extend has been removed, as far as I can see there's now defineComponent, but it does not seem to work the same way.

I get the following error when I just try and replace it 1-1: TypeError: ComponentClass is not a constructor

Has anyone tried something similar, or know how to fix this?

Top answer
1 of 4
17

Use createApp instead of Vue.extend here's a example of simple vue3 components programmatically

import Button from 'Button.vue'
import { createApp } from "vue"
// Creating the Instance
// use createApp https://v3.vuejs.org/api/global-api.html#createapp
var ComponentApp = createApp(Button)
import Button from "./Button.vue"

// inserting to dom
const wrapper = document.createElement("div")
ComponentApp.mount(wrapper)
document.body.appendChild(wrapper)

set props or slot is a little different by use h, https://v3.vuejs.org/api/global-api.html#h

import Button from 'Button.vue'
import { createApp, h } from "vue"

var ComponentApp = createApp({ 
  setup () {
    return () => h(Button, {type: "primary"}, "default slot as children")
  }
})
2 of 4
7

If I understood you correctly, then the solution will be like this

You can learn more about 'defineAsyncComponent' on the official website https://v3.vuejs.org/api/global-api.html#defineasynccomponent

<template>
    <button @click="addTag()" type="button">Add new tag</button>
    <br>
    <div>
        <div v-for="child in children" :key="child.name">
            <component :is="child"></component>
        </div>
    </div>
</template>

<script>

import { defineAsyncComponent, defineComponent, ref } from "vue"

export default defineComponent({
components: {     
      UploadTaskTag: defineAsyncComponent(() => import("./UploadTaskTag"))
    },
 setup() {
      const children = ref([])

      const addTag = () => {
        children.value.push('UploadTaskTag')
        console.log(children.value)
      }
return {
        addTag,
        children        
      }
    },
  })
</script>
🌐
Medium
papereyra.medium.com › dynamically-loading-vue-3-components-a-composable-approach-d17a25e21fd5
Dynamically Loading Vue 3 Components: A Composable Approach | by Pamela Pereyra | Medium
December 20, 2023 - If there is no existing Vue app instance (app is null), it creates a new app instance using createApp and mounts the ConfirmDialog component to a dynamically created container element in the document body.
🌐
DevPress
devpress.csdn.net › vue › 63174a4c237eb178e9dfbcdb.html
How to programmatically create a component instance in Vue 3?_javascript_Vue小助理-Vue
Here's how to do with createApp in Vue 3, but the context (stores, plugins, directives...) will not be kept. // 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.remvoeChild(mountEl); dialog.unmount(); dialog = null; }, }); dialog.mount(mountEl); }, };
🌐
Stack Overflow
stackoverflow.com › questions › 61887321 › how-do-i-create-a-component-instance-programmatically-in-vue-3
vue.js - How do I create a component instance programmatically in vue 3? - Stack Overflow
Therefore, you cannot create an instance of this component. But there is a workaround for that. const TooltipClass = Vue.extend(tooltip); const tooltipInstance = new TooltipClass() Vue.extend creates a subclass of the Vue constructor. Hope this helps! ... I've seen examples of your suggestion working in vue, version 2. I tried to: Import Vue from 'vue' and 'extend' as you suggest, but in vue, version 3, I'm getting the error: 'cannot read property of undefined'.
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › how-to-programmatically-create-a-component-instance-in-vue-3
Creating a Vue 3 Component Instance Programmatically: A Guide - Javascript
March 26, 2023 - Jim, I appreciate your reply. After extensive research, I found the solution to my problem in this article: https://css-tricks.com/ creating-vue-js-component -instances-programmatically/. To resolve it, I utilized the Vue.extend function to duplicate MyDataGrid component, as presented below.
🌐
JavaScript in Plain English
javascript.plainenglish.io › vue-3-programmatic-component-design-a1a20f853a4b
Vue 3 Programmatic Component Design | by Abhimanyu Chauhan | JavaScript in Plain English
January 24, 2022 - Follow to join our 3.5M+ monthly readers. ... If you ever have used any design-system library, there is a common component each of them provides related to Typography. It would provide a prop where you define the tag line as or variant. And the next thing you see is it renders the element you defined in the prop. This pattern is often referred to as creating component instances programmatically.
🌐
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.
🌐
CSS-Tricks
css-tricks.com › creating-vue-js-component-instances-programmatically
Creating Vue.js Component Instances Programmatically | CSS-Tricks
January 23, 2018 - I have been on a Vue.js project that required the ability to create components programmatically. By programmatically, I mean you create and insert the components completely from JavaScript, without writing anything in the template. This article aims to illustrate how different aspects of using ...
🌐
Medium
medium.com › geekculture › dynamic-components-in-vue-3-7504d5ffcb6c
Dynamic components in Vue 3.. Create dynamic components from JSON . | by Hariprasad K.B | Geek Culture | Medium
June 23, 2021 - Now we will create a DynamicRenderer component which will select required component from the value of type in the JSON. Now you would have noticed the values in type are the component name’s. ... In this DynamicRenderer the main flexibility that Vue provides is <component></component> which is a Dynamic component which can take any component and dynamically render them (we can also conditionally render with v-if ).
🌐
YouTube
youtube.com › overseas media
Vue: Mount a component programmatically (4 lines of code) - YouTube
Jump to 5:05 for the actual code. This video will show you how to mount a component in Vue programmatically for whatever reason you wanna do that, i explain ...
Published   April 15, 2020
Views   674
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 69651955 › creating-vue-3-component-instances-programmatically
Creating Vue 3 Component Instances Programmatically
I have the following code in Vue 2 import MyComponent from './MyComponent.vue' let ComponentClass, instance let propsData = {} ComponentClass = Vue.extend(component) instance = new ComponentClass({
🌐
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
Create a <script></script> section below your template section. Inside the <script> tags, add a default exported object export default {}, which is your component object. ... We can now begin to add actual content to our ToDoItem. Vue templates are currently only allowed a single root element ...
🌐
Stack Overflow
stackoverflow.com › questions › 77362556 › how-to-create-component-instance-programmatically-in-vue-3
vue.js - How to create component instance programmatically in Vue 3? - Stack Overflow
October 25, 2023 - Each step is a Vue component that knows how to operate their piece of data. Each step has a restore function that has the logic to restore the object in that particular step. There are some specific steps that require navigation away from the app (like connecting a Google calendar with OAuth flow). During return to the application I need to restore the object up until the current step. And since each step owns their piece of data I was using Vue.extend to create previous steps and I was calling the restore method of each step.
🌐
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