Vue3第10课:Suspense异步组件使用真实请求深入学习与onErrorCaptured获取异步请求异常

发布于:2023-05-09 ⋅ 阅读:(366) ⋅ 点赞:(0)

上一篇使用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>

alt

alt

当请求到图片后,从loading变成加载图片

当异步请求出现错误时,我们使用onErrorCaptured捕获错误

使用前需要进行引入

import { onErrorCaptured } from "vue";

有了onErrorCaptured就可以直接在setup()函数中直接使用了。钩子函数要求我们返回一个布尔值,代表错误是否向上传递,我们这里返回了true

 onErrorCaptured((error) => {
   console.log(`error====>`, error);
   return true;
 });

写好后,我们故意把请求地址写错,然后打开浏览器的终端,看一下控制台已经捕获到错误了。
alt

alt

本文含有隐藏内容,请 开通VIP 后查看