13. Suspense组件-深入学习 真实请求
上节我们是一个假的异步请求,利用了setTimeOut()
方法来模拟异步请求,当然这也很恰当的演示了Suspense
的使用方法。本节我们就深入一下,用以前请求北海九号餐厅三大美女服务员的 API 真实接口来继续深入学习一下。
编写随机美女的异步组件
在/src/components/
目录下,新建一个GirlShow.vue
的新组件。
我们先来写个基本的模板,其实你可以把这段代码复制进你的程序,因为这段代码你一定打过很多遍了。
<template> </template> <script lang="ts"> import axios from 'axios' import { defineComponent } from 'vue' export default defineComponent({ setup() { } }) </script>
再向下写,需要注意的是,上节课的例子,我们返回的是一个promise
对象,其实我个人是不喜欢promise
这种写法的,我更喜欢用async...await
的写法,它是promise
的语法糖。建议你在工作中也尽量的使用async...await
的写法。
Suspense
也是支持async...await
的语法的,所以这个组件就用async
的写法来写。
<template> <img :src="result && result.imgUrl" /> </template> <script lang="ts"> import axios from 'axios' import { defineComponent } from 'vue' export default defineComponent({ async setup() { //promise 语法糖 返回之后也是 promise 对象 const rawData = await axios.get('https://api.mybj123.com/default/getGirl') return {result:rawData.data} } }) </script>
这样组件就编写完成了,看起来是比纯Promise
的写法好看很多了。
引入组件并使用 Suspense 组件
打开App.vue
页面,然后先用import
引入GirlShow.vue
。
import GirlShow from "./components/GirlShow.vue";
然后在components
中声明一下,就可以在模板中使用了
const app = { name: "App", components: { AsyncShow, GirlShow }, setup() { return {}; }, };
模板部分代码:
<template> <div> <Suspense> <template #default> <girl-show /> </template> <template #fallback> <h1>Loading...</h1> </template> </Suspense> </div> </template>
这部分写完,就可以打开服务yarn serve
,然后到http://localhost:8080/
预览一下结果哦。注意,我的服务器设置了缓存,所以你可能几次刷新都会是同一张照片,这个不是你的问题。但你也要注意,自己是不是也有图片缓存。
处理异步请求错误
在异步请求中必须要作的一件事情,就是要捕获错误,因为我们没办法后端给我们返回的结果,也有可能服务不通,所以一定要进行捕获异常和进行处理。
在vue3.x
的版本中,可以使用onErrorCaptured
这个钩子函数来捕获异常。在使用这个钩子函数前,需要先进行引入。
import { ref , onErrorCaptured} from "vue";
有了onErrorCaptured
就可以直接在setup()
函数中直接使用了。钩子函数要求我们返回一个布尔值,代表错误是否向上传递,我们这里返回了true
。
const app = { name: "App", components: { AsyncShow, GirlShow }, setup() { onErrorCaptured((error) => { console.log(`error====>`,error) return true }) return {}; }, };
写好后,我们故意把请求地址写错,然后打开浏览器的终端,看一下控制台已经捕获到错误了。
在实际工作中,你可以根据你的真实需求,处理这些错误。我这里就不做过多的演示啦。
码云笔记 » 13. Suspense组件-深入学习 真实请求