Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic component in Vue3 Composition API

Tags:

vuejs3

A simple working example of a Vue2 dynamic component


<template>
    <div>
        <h1>O_o</h1>
        <component :is="name"/>
        <button @click="onClick">Click me !</button>
    </div>
</template>

<script>
    export default {
        data: () => ({
            isShow: false
        }),
        computed: {
            name() {
                return this.isShow ? () => import('./DynamicComponent') : '';
            }
        },
        methods: {
            onClick() {
                this.isShow = true;
            }
        },
    }
</script>

Everything works, everything is great. I started trying how it would work with the Composition API.

<template>
    <div>
        <h1>O_o</h1>
        <component :is="state.name"/>
        <button @click="onClick">Click me !</button>
    </div>
</template>

<script>
    import {ref, reactive, computed} from 'vue'

    export default {
        setup() {
            const state = reactive({
                name: computed(() => isShow ? import('./DynamicComponent.vue') : '')
            });

            const isShow = ref(false);

            const onClick = () => {
                isShow.value = true;
            }

            return {
                state,
                onClick
            }
        }
    }
</script>

We launch, the component does not appear on the screen, although no errors are displayed.

like image 574
Oleksii Zelenko Avatar asked Dec 10 '25 12:12

Oleksii Zelenko


1 Answers

You can learn more about 'defineAsyncComponent' here https://labs.thisdot.co/blog/async-components-in-vue-3

or on the official website https://v3.vuejs.org/api/global-api.html#defineasynccomponent

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

export default defineComponent({
setup(){
const isShow = ref(false);
const name = computed (() => isShow.value ? defineAsyncComponent(() => import("./DynamicComponent.vue")): '')

const onClick = () => {
    isShow.value = true;
  }
 }
})
like image 114
Oleksii Zelenko Avatar answered Dec 13 '25 10:12

Oleksii Zelenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!