一文搞懂Vue3中的異步組件defineAsyncComponentAPI的用法
前言
當我們的項目達到一定的規(guī)模時,對于某些組件來說,我們并不希望一開始全部加載,而是需要的時候進行加載;這樣的做得目的可以很好的提高用戶體驗。
為了實現(xiàn)這個功能,Vue3中為我們提供了一個方法,即defineAsyncComponent,這個方法可以傳遞兩種類型的參數(shù),分別是函數(shù)類型和對象類型,接下來我們分別學習。
傳遞工廠函數(shù)作為參數(shù)
defineAsyncComponent方法接收一個工廠函數(shù)是它的基本用法,這個工廠函數(shù)必須返回一個Promise,Promise的resolve應(yīng)該返回一個組件。
我們這里以Vue Cli創(chuàng)建的項目為例,這里我稍微做了一下修改,將頭部的圖片拆分為一個組件,代碼如下:
<template> <logo-img /> <hello-world msg="Welcome to Your Vue.js App" /> </template> <script setup> import LogoImg from './components/LogoImg.vue' import HelloWorld from './components/HelloWorld.vue' </script>
現(xiàn)在我們就將<hello-world>組件修改為異步組件,示例代碼如下:
<template>
<logo-img />
<hello-world msg="Welcome to Your Vue.js App" />
</template>
<script setup>
import { defineAsyncComponent } from 'vue'
import LogoImg from './components/LogoImg.vue'
// 簡單用法
const HelloWorld = defineAsyncComponent(() =>
import('./components/HelloWorld.vue'),
)
</script>我們這里為了看到效果,將import延遲執(zhí)行,示例代碼如下:
<script setup>
import { defineAsyncComponent } from 'vue'
import LogoImg from './components/LogoImg.vue'
// 定義一個耗時執(zhí)行的函數(shù),t 表示延遲的時間, callback 表示需要執(zhí)行的函數(shù),可選
const time = (t, callback = () => {}) => {
return new Promise(resolve => {
setTimeout(() => {
callback()
resolve()
}, t)
})
}
// 定義異步組件,這里這樣寫是為了查看效果
const HelloWorld = defineAsyncComponent(() => {
return new Promise((resolve, reject) => {
;(async function () {
try {
await time(2000)
const res = await import('./components/HelloWorld.vue')
resolve(res)
} catch (error) {
reject(error)
}
})()
})
})
</script>代碼運行結(jié)果如下所示:

當2s后才會加載<hello-world>組件。
傳遞對象類型作為參數(shù)
defineAsyncComponent方法也可以接收一個對象作為參數(shù),該對象中有如下幾個參數(shù):
loader:同工廠函數(shù);loadingComponent:加載異步組件時展示的組件;errorComponent:加載組件失敗時展示的組件;delay:顯示loadingComponent之前的延遲時間,單位毫秒,默認200毫秒;timeout:如果提供了timeout,并且加載組件的時間超過了設(shè)定值,將顯示錯誤組件,默認值為Infinity(單位毫秒);suspensible:異步組件可以退出<Suspense>控制,并始終控制自己的加載狀態(tài)。onError:一個函數(shù),該函數(shù)包含4個參數(shù),分別是error、retry、fail和attempts,這4個參數(shù)分別是錯誤對象、重新加載的函數(shù)、加載程序結(jié)束的函數(shù)、已經(jīng)重試的次數(shù)。
如下代碼展示defineAsyncComponent方法的對象類型參數(shù)的用法:
<template>
<logo-img />
<hello-world msg="Welcome to Your Vue.js App" />
</template>
<script setup>
import { defineAsyncComponent } from 'vue'
import LogoImg from './components/LogoImg.vue'
import LoadingComponent from './components/loading.vue'
import ErrorComponent from './components/error.vue'
// 定義一個耗時執(zhí)行的函數(shù),t 表示延遲的時間, callback 表示需要執(zhí)行的函數(shù),可選
const time = (t, callback = () => {}) => {
return new Promise(resolve => {
setTimeout(() => {
callback()
resolve()
}, t)
})
}
// 記錄加載次數(shù)
let count = 0
const HelloWorld = defineAsyncComponent({
// 工廠函數(shù)
loader: () => {
return new Promise((resolve, reject) => {
;(async function () {
await time(300)
const res = await import('./components/HelloWorld.vue')
if (++count < 3) {
// 前兩次加載手動設(shè)置加載失敗
reject(res)
} else {
// 大于3次成功
resolve(res)
}
})()
})
},
loadingComponent: LoadingComponent,
errorComponent: ErrorComponent,
delay: 0,
timeout: 1000,
suspensible: false,
onError(error, retry, fail, attempts) {
// 注意,retry/fail 就像 promise 的 resolve/reject 一樣:
// 必須調(diào)用其中一個才能繼續(xù)錯誤處理。
if (attempts < 3) {
// 請求發(fā)生錯誤時重試,最多可嘗試 3 次
console.log(attempts)
retry()
} else {
fail()
}
},
})
</script>上面的代碼中,我們加載組件時前兩次會請求錯誤,只有第三次加載才會成功,代碼運行結(jié)果如下:

如果加載失敗則會展示ErrorComponent組件。
總結(jié)
到此這篇關(guān)于一文搞懂Vue3中的異步組件defineAsyncComponentAPI的用法的文章就介紹到這了,更多相關(guān)Vue3異步組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue+vuex+json-seiver實現(xiàn)數(shù)據(jù)展示+分頁功能
這篇文章主要介紹了vue+vuex+json-seiver實現(xiàn)數(shù)據(jù)展示+分頁功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04
vue+bpmn.js實現(xiàn)自定義流程圖的完整代碼
這篇文章主要介紹了vue+bpmn.js實現(xiàn)自定義流程圖的完整代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借價值,需要的朋友參考下吧2024-03-03
vue 彈窗時 監(jiān)聽手機返回鍵關(guān)閉彈窗功能(頁面不跳轉(zhuǎn))
這篇文章主要介紹了vue 彈窗時 監(jiān)聽手機返回鍵關(guān)閉彈窗功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值(頁面不跳轉(zhuǎn)) ,需要的朋友可以參考下2019-05-05

