子组件
my-project\src\components\DogShow.vue
<template><img :src="result && result.message" />
</template>
<script lang="ts">
import axios from "axios";
import { defineComponent } from "vue";
export default defineComponent({async setup() {// vue3 suspense async await语法const rawData = await axios.get("https://dog.ceo/api/breeds/image/random");// 此处把url故意写错,为了onErrorCaptured 抓取错误// const rawData = await axios.get("https://dog.ceo/api/breeds/image");return {result: rawData.data,};},
});
</script>
父组件
<template><h2>{{ error }}</h2><Suspense><!-- 请求成功返回的数据 --><template #default><dog-show /></template><!-- 请求失败显示的数据 --><template #fallback><h1>Loading !...</h1></template></Suspense>
</template>
<script lang="ts">
import DogShow from "./components/DogShow.vue";
import {onErrorCaptured,
} from "vue";
export default {name: "App",components: {DogShow,},setup() {const error = ref(null); // onErrorCaptured 抓取错误onErrorCaptured((e: any) => {error.value = e;// 此处表示错误是否要向上传播return true;});return {error};}</script>
suspense async await用法效果:先出现loading!..,再出现图片
把换成DogShow.vue中请求的url换成错误的,如 https://dog.ceo/api/breeds/image
onErrorCaptured 抓取错误效果:先出现loading!..,再出现错误信息