How to use Vue3 asynchronous data loading component suspense

  • 2021-11-10 08:36:18
  • OfStack

Directory Preface Creation Component
Summarize

Preface

Vue3 has added many features that make people shine at the moment, and suspense component is one of them, which is very practical for processing asynchronous request data. This paper introduces its usage through simple examples. If you are interested in it, please refer to the official documents.

Usually it is common for a component to execute some kind of asynchronous request before it is rendered properly, usually by designing a mechanism by which developers deal with this problem, and there are many good ways to fulfill this requirement.

For example, retrieving data asynchronously from an API and wanting to display information such as loading effect when the retrieved response data is parsed, the suspense component can be used in Vue3 to perform such a requirement.

Create a component

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>

ref will be introduced here to ensure the reactivity of component state. Therefore, according to the above code snippet, the movie data is obtained through asynchronous API call.
For HTTP requests initiated in VUE projects, Axios is usually used, and fetch is tried here.

OK, now let's use suspense to display the information in the data load within the application.

Modify the App. vue file to code as follows:


<template>
    <div>
        <h1> Star Wars characters </h1>
    </div>
    <suspense>
        <template #default>
            <CyPeoples />
        </template>
        <template #fallback>
            <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>

From the above code snippet, the effect of loading can be easily achieved using the component suspense, with # default as the initialization template component, showing UI after the asynchronous request is completed. With # fallback is the processing UI in asynchronous requests, which is the common loading effect.

Summarize

The suspense component is a new feature of Vue3 that simplifies the processing logic for asynchronous requests to UI.


Related articles: