示例
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 
 | <template><div>
 <h1>Vue3 懒加载的组件简单示例</h1>
 
 <button @click="showComponent = !showComponent">Toggle Lazy Loaded Component</button>
 <Suspense>
 
 <template #default>
 <LazyComponent v-if="showComponent" />
 </template>
 <template #fallback>
 <p>Loading...</p>
 </template>
 </Suspense>
 </div>
 </template>
 
 <script setup>
 
 import { ref } from 'vue'
 import { defineAsyncComponent } from 'vue'
 
 const showComponent = ref(false)
 
 
 const LazyComponent = defineAsyncComponent(() => import('./LazyComponent.vue'))
 </script>
 
 | 
使用 defineAsyncComponent 来定义懒加载的组件。
import('./LazyComponent.vue') 会在需要时才加载 LazyComponent。
Suspense 标签提供了加载中的占位符(fallback),当懒加载的组件还没加载完成时,显示一个 loading 提示。
这样,当点击按钮时,懒加载的 LazyComponent 就会按需加载,提升页面加载性能。
LazyComponent.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | <template><div>
 <p>This is a lazy-loaded component!</p>
 </div>
 </template>
 
 <script setup>
 
 </script>
 
 |