首页 > 解决方案 > 为什么动态组件在 vue3 中不起作用?

问题描述

这是一个有效的 Vue2 示例:

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

在 Vue3 选项下重做不起作用。不会发生错误,但不会出现组件。

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

有人研究过vue2 beta版吗?请帮帮我。抱歉语言笨拙,我使用谷歌翻译。

标签: vue.jsvuejs3

解决方案


将模板中的所有内容都保留在 Vue2 中

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

仅在“设置”中使用 defineAsyncComponent 进行更改

您可以在此处了解有关 defineAsyncComponent 的更多信息 https://labs.thisdot.co/blog/async-components-in-vue-3

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

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

推荐阅读