[This is the third day of my participation in the August More Text Challenge. For details, see: August More Text Challenge]

The Suspense component is one of the many exciting enhancements to Vue3 that makes it useful for handling asynchronous request data. This article shows you how to use it with simple examples, and you can refer to the official documentation for those interested.

It’s very common for a component to need to perform some kind of asynchronous request before it can be rendered properly, usually by designing a mechanism by which developers can handle the problem, and there are many good ways to achieve this requirement.

For example, fetching data asynchronously from an API and wanting to show some information, such as loading effects, when the fetching response data has been parsed, you can use the Suspense component in Vue3 to perform such a requirement.

Create components

Create a component and name it Peoples. Vue with the following component code:

<template> <div v-for="(people, index) in peoples.results" :key="index"> {{ people.name }} {{ people.birth_year }} </div> </template> <script> import { ref } from "vue"; export default { name: "CyPeoples", async setup() { const peoples = ref(null); const headers = { "Content-Type": "application/json" }; const fetchPeoples = await fetch("https://swapi.dev/api/people", { headers, }); peoples.value = await fetchPeoples.json(); return { peoples }; }}; </script>Copy the code

The REF is introduced here to ensure the reactivity of the component state. So, according to the code snippet above, get the movie data through an asynchronous API call.

For MAKING AN HTTP request in a VUE project, usually using Axios, the FETCH is attempted.

Ok, now let’s use Suspense to show information about data loads in your application.

Modify the app.vue file to look like this:

< span style = "box-sizing: border-box! Important; word-break: break-word! Important; word-break: break-word! Important; word-break: break-word! Important; word-break: break-word! Important;" <div> <h3> Data loading...... </h3> </div> </template> </suspense> </template> <script> import CyPeoples from "./components/Peoples.vue"; import { suspense } from "vue"; export default { name: "App", components: { CyPeoples, suspense, }, }; </script>Copy the code

From the code snipple above, you can easily implement a loading effect using the component Suspense, showing the UI after the asynchronous request has completed with #default as the initial template component. With #fallback for asynchronous request processing UI, i.e. common loading effect.

conclusion

The Suspense component is a new feature of Vue3 that simplifies the processing logic of asynchronous request UIs.