
上一篇使用setTimeout
模拟了异步请求,这一篇使用真实请求。
Suspense
也是支持async...await
的语法的,所以这个组件就用async
的写法来写
DogShow.vue
<template>
<div class="dogshow">
<img :src="result.message" alt="" srcset="" />
</div>
</template>
<script lang="ts">
import axios from "axios";
import { defineComponent } from "vue";
export default defineComponent({
name: "dogshow",
async setup() {
const rawData = await axios.get("https://dog.ceo/api/breeds/image/random");
return { result: rawData.data };
},
components: {},
});
</script>
<style lang="scss" scoped>
.dogshow {
}
</style>
在App.vue中使用
<Suspense>
<template #default>
<DogShow></DogShow>
</template>
<template #fallback>
<h1>loading......</h1>
</template>
</Suspense>
当请求到图片后,从loading变成加载图片
当异步请求出现错误时,我们使用onErrorCaptured
捕获错误
使用前需要进行引入
import { onErrorCaptured } from "vue";
有了onErrorCaptured
就可以直接在setup()
函数中直接使用了。钩子函数要求我们返回一个布尔值,代表错误是否向上传递,我们这里返回了true
。
onErrorCaptured((error) => {
console.log(`error====>`, error);
return true;
});
写好后,我们故意把请求地址写错,然后打开浏览器的终端,看一下控制台已经捕获到错误了。