如何动态导入 Vue 3 组件?
How to dynamically import Vue 3 component?
根据 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 3 中使用 defineAsyncComponent
来延迟加载组件
import { defineAsyncComponent } from 'vue'
...
components: {
LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
}
https://v3.vuejs.org/guide/migration/async-components.html#overview
根据 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 3 中使用 defineAsyncComponent
来延迟加载组件
import { defineAsyncComponent } from 'vue'
...
components: {
LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
}
https://v3.vuejs.org/guide/migration/async-components.html#overview