Vue——vue3 suspense async await用法 && onErrorCaptured 抓取错误

子组件

my-project\src\components\DogShow.vue


<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>

父组件


<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!..,再出现错误信息

Vue——vue3 suspense async await用法 && onErrorCaptured 抓取错误_第1张图片

你可能感兴趣的:(VUE,vue.js,前端)