核心概念與使用方式
定義異步組件
-
defineAsyncComponent函數(shù)(Vue3推薦方式)
定義一個(gè)異步組件,它在運(yùn)行時(shí)是懶加載的。參數(shù)可以是一個(gè)異步加載函數(shù),或是對(duì)加載行為進(jìn)行更具體定制的一個(gè)選項(xiàng)對(duì)象。
import { defineAsyncComponent } from 'vue';
const AsyncCom = defineAsyncComponent(() => import('./MyComponent.vue'));
// 具體配置
const AsyncComp = defineAsyncComponent({
loader: () => import('./MyComponent.vue'),
loadingComponent: loadingSpinner, // 加載中組件
errorComponent: ErrorDisplay, // 錯(cuò)誤組件
delay: 1000, // 延遲顯示loading(防閃爍)
timeout, // 超時(shí)時(shí)間
})
異步組件的核心作用
- 按需加載:減少初始包體積,提升首屏加載速度
- 性能優(yōu)化:結(jié)合代碼分割(Code Spliting)動(dòng)態(tài)加載非關(guān)鍵組件
應(yīng)用場(chǎng)景
- 大型應(yīng)用模塊懶加載:如管理后臺(tái)的復(fù)雜表單/圖表組件
- 條件渲染組件:用戶交互后才加載的非必要組件(如彈窗)
- 路由級(jí)懶加載:結(jié)合Vue Router提升首屏性能
Suspense和異步組件的關(guān)系
Suspense:內(nèi)置組件,用于統(tǒng)一管理異步組件的加載狀態(tài)(如多個(gè)異步組件并行加載)
異步組件:通過(guò)defineAsyncComponent定義,由Suspense控制占位內(nèi)容
<template>
<Suspense>
<template #default>
<AsyncComp />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</template>
如何實(shí)現(xiàn)組件加載失敗后的重試邏輯
工廠函數(shù)返回Promise:在loader中捕獲錯(cuò)誤并重試
const Async = defineAsyncComponent({
loader: () => import('./MyComponent.vue')
.catch(() => {
// 重試邏輯
return retryImport();
})
})
異步組件在路由懶加載中的應(yīng)用
Vue Router配置:
const router = createRouter({
route: [{
path: '/profile',
component: () => import('./Profile.vue'); // 直接動(dòng)態(tài)導(dǎo)入
// 或使用defineAsyncComponent
component: defineAsyncComponent(() => import('./Profile.vue'))
}]
})
Vue3異步組件與Vue2的差異
-
語(yǔ)法差異:Vue3廢棄Vue.component('async-comp',() => import(...)),改用
defineAsyncComponent -
功能增強(qiáng):Vue3支持更細(xì)顆粒度的加載狀態(tài)管理和
Suspense集成
代碼實(shí)例
// 異步組件定義
const AsyncModal = defineAsyncComponent({
lodaer: () => import('./Modal.vue').catch((err) ==> {
console.log('加載失敗,3s后重試...');
return new Promise(resolve => {
setTimeout(() => resolve(import('./Modal.vue')), 3000);
})
}),
loadingComponent: LoadingSpainner,
delay: 200,
timeout: 5000
});
// 在組合式API中使用
export default {
setup() {
const showModal = ref(false);
return { showModal, AsyncModal };
}
}