为什么动态组件在vue3中不起作用?

pro*_*ova 9 vue.js vuejs3

这是一个有效的 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>
Run Code Online (Sandbox Code Playgroud)

Vue3 下的 Redone 选项不起作用。没有发生错误,但组件没有出现。

<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>
Run Code Online (Sandbox Code Playgroud)

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

Ole*_*nko 10

像 Vue2 中一样将所有内容保留在模板中

<template>
    <div>
        <h1>O_o</h1>
        <component :is="name"/>
        <button @click="onClick">Click me !</button>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

使用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;
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这正在解决 Vue 3 和安装异步组件的问题。这应该被接受为答案。 (2认同)