Suspense組件是Vue3中的知名功能之一,
它們允許我們的應用程式在等待異步組件時渲染一些后備內容,可以讓我們創建一個平滑的用戶體驗,
值得慶幸的是,Suspense組件非常容易理解,它們甚至不需要任何額外的匯入!
可以解決異步請求的困境; Suspense是Vue3推出的一個內置的特殊組件; 如果使用Suspense,需要回傳一個Promise
本文主要是展示一哈加載多個異步組件的場景,遇到不穩定問題,及解決方法(加載單個,只需要引入單個組件即可)
創建第一個組件:
AsyncShow
<!--
* @Description: Suspense - 異步請求好幫手
* @Author: Rulyc
* @Operating:
-->
<template>
<h1>{{ result }}</h1>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: "10_AsyncShow",
setup() {
/** 需要回傳一個Promise, 使用Suspense */
return new Promise((resolve) => {
setTimeout(()=>{
return resolve({
result: 42
})
}, 3000)
})
}
})
</script>
使用 async await , 新建一個 10_AsyncShow_Img組件
<template>
<img :src="result && result.url" alt="">
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
export default defineComponent({
name: "10_AsyncShow",
async setup() {
const rawData = await axios.get('https://images.dog.ceo/breeds/terrier-irish/n02093991_4404.jpg')
return {
result: rawData.config
}
}
})
</script>
app中:(自行引入兩個組件,然后使用如下圖中)


警告中說:是一個實驗性的特性,它的API很可能會改變slots,除非只有一個根節點,在
故而這里目前應該暫時展示一個根節點(之前的版本中,是可以展示多個異步組件作為根節點的; 以后版本未確定,還不夠穩定)
解決這個問題,初步采用了增加一個div包裹(即增加一個根節點)
<Suspense>
<template #default>
<div>
<AsyncShow></AsyncShow>
<AsyncShowImg></AsyncShowImg>
</div>
</template>
<template #fallback>
<div>
Loading... ---- 異步加載中
</div>
</template>
</Suspense>
在4.5.8版本中,是需要增加一個根節點的,目前博主使用的是4.5.8; 之前的版本貌似是不用增加一個根節點,

補充:
單個組件及template上屬性說明如下圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/233145.html
標籤:其他
