现有父子组件如下:
父组件
<template>
<div class="father">
<h3>父组件</h3>
<Son />
</div>
</template>
<script setup lang="ts">
import Son from "./Son.vue"
</script>
<style scoped>
.father {
width: 400px;
height: 400px;
background-color: #bfd6ff;
}
</style>
子组件:组件顶层带有await
表达式
<template>
<div class="son">
<h4>子组件</h4>
</div>
</template>
<script setup lang="ts">
import axios from "axios"
await axios("https://api.uomg.com/api/rand.qinghua?format=json")
</script>
<style scoped>
.son {
width: 200px;
height: 200px;
border: 1px solid #000;
}
</style>
使用
与React中的Suspense类似,但是目前仍为实验性功能:
由于子组件中出现上图中情况1:await表达式。所以父组件中无法正确展示子组件,需要使用Suspense内置组件,将未成功渲染的子组件包裹即可。
<Suspense>
<Son />
</Suspense>
但通过控制台将网速变为3G后可以明显发现,在接口完成之前,有一段时间子组件内容区域为空白。
可以在接口数据返回前,展示另一种结构优化体验。
由于底层使用插槽实现,所以在Suspense下加入template且插槽名为fallback。
<Suspense>
<Son />
<template #fallback>
<p>加载中...</p>
</template>
</Suspense>
父组件
<template>
<div class="father">
<h3>父组件</h3>
<Suspense>
<Son />
<template #fallback>
<p>加载中...</p>
</template>
</Suspense>
</div>
</template>
<script setup lang="ts">
import Son from "./Son.vue"
</script>
<style scoped>
.father {
width: 400px;
height: 400px;
background-color: #bfd6ff;
}
</style>