Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 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 Answer

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;
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...