【问题标题】:How to dynamically import Vue 3 component?如何动态导入 Vue 3 组件?
【发布时间】:2021-10-04 03:08:24
【问题描述】:

根据this article,我想导入组件以动态查看我的 Vue 3 应用程序。视图代码如下:

<template>
  <div class="page">
      <latest-box v-if="showLatestBox" />
  </div>
</template>


<script>
// @ is an alias to /src
// This works well. 
//import LatestBox from '@/components/LatestBox.vue'


export default {
    name: 'Page 1',

    data() {
        return {
            showLatestBox: true,
        }
    },

    components: {
        LatestBox: () => import('@/components/LatestBox.vue')  // This does not work
    }
}
</script>

代码不会抛出任何错误,但我没有在页面上看到该组件。如果我使用第一个导入样式,它会起作用。我错过了什么吗?

【问题讨论】:

    标签: vue.js import components vuejs3


    【解决方案1】:

    你需要在Vue 3中使用defineAsyncComponent来延迟加载组件

    import { defineAsyncComponent } from 'vue'
    ...
        components: {
            LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
        }
    

    https://v3.vuejs.org/guide/migration/async-components.html#overview

    【讨论】:

    • 好的,谢谢!
    猜你喜欢
    • 2020-02-25
    • 2019-04-23
    • 2021-03-30
    • 2020-06-18
    • 2019-02-03
    • 2021-11-23
    • 2020-01-24
    • 2022-01-09
    • 2021-11-09
    相关资源
    最近更新 更多