This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

For Vue3, which has been out for a while, there are many new features worth learning. I have also explored and learned intermittently, but it is not too systematic and there is no summary. Here I make some summary of learning, record && accumulation!

Several previous articles began with a summary of Vue3 learning:

  • Vue3 had its first taste,
  • Vue3 lifecycle and setup() function,
  • computed & watch ,
  • TeleportChanges the root node on which the component is mounted

Suspense continues in this article: Suspense is a new feature for Vue3

Suspense

! Suspense is an experimental new feature and should not be used in production environments.

Suspense Chinese documents address: v3.cn.vuejs.org/guide/migra…

Of course, you can also look at the English document –:

Suspense English Documentation Address: v3.vuejs.org/guide/migra…

Suspense what is Suspense?

Suspense asking for good help, to start with a little chestnut:

1. Define an asynchronous component first:AsyncShow.vue

Define an asynchronous component: AsyncShow. Vue returns a Promise in setup:

/// AsyncShow.vue
<template>
  <h1>{{ result }}</h1>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  setup() {
    return new Promise((resolve) = > {
      setTimeout(() = > {
        return resolve({
          result: 213})},213)})}})</script>
Copy the code

2. Use it in the App:

It is common to make some asynchronous requests before rendering components properly. Components typically handle this logic locally, which is perfectly fine in most cases.

Suspense allows you to add multiple asynchronous components:

/// App.vue
<template>
  <suspense>
    <template #default>
      <async-show />
    </template>
    <template #fallback>
      <h1>Loading ...</h1>
    </template>
  </suspense>
</template>

<script lang="ts">
  export default {
    components: {
      AsyncShow: defineAsyncComponent(() = > import('./AsyncShow.vue')),}},</script>
Copy the code

Suspense > Components have two slots. They both accept only one direct child node.

  • defaultNodes in slots are displayed as much as possible.
  • If not, show itfallbackNodes in slots.

It is important that asynchronous components do not need to be direct children of Suspense >. It can appear at any depth in the component tree

Another way to trigger a fallback is to have descendant components return a Promise in the setup function:

export default {
  async setup() {
    const data = await loadData()
    return {
      // ...}}},Copy the code