Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

vuejs3 - Dynamic component in Vue3

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.

question from:https://stackoverflow.com/questions/65950655/dynamic-component-in-vue3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The component should be added to components option then just return it name using the computed property based on the ref property isShow :

components:{
   MyComponent:defineAsyncComponent(() => import("./DynamicComponent.vue"))
},
setup(){
const isShow = ref(false);
const name = computed (() => isShow.value ? 'MyComponent': '')

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...