Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue3 Creating Component Instances Programmatically on button click

In vue2 it was be easy:

<template>
 <button :class="type"><slot /></button>
</template>
<script>
 export default {
   name: 'Button',
   props: [ 'type' ],
 }
</script>
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 image 367
Artemiy Avatar asked Oct 07 '20 20:10

Artemiy


2 Answers

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)
like image 200
Artemiy Avatar answered Sep 30 '22 19:09

Artemiy


This works for me, using options API, in a method create a component


import { defineComponent } from "vue";


createComponent() {
var component = {
   data() {
      return {
         hello:'world',
      }
   },
   template:`<div>{{hello}}</div>`
}

var instance = defineComponent(component);

}

Use it within your template once you've instantiated it

<component :is="instance" v-if="instance"/>
like image 31
Cade Embery Avatar answered Sep 30 '22 20:09

Cade Embery