欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3異步組件Suspense的使用方法詳解

 更新時(shí)間:2023年01月26日 12:49:10   作者:Nanchen_42  
這篇文章主要介紹了Vue3異步組件Suspense的使用方法詳解,需要的朋友可以參考下

Suspense組件

官網(wǎng)中有提到他是屬于實(shí)驗(yàn)性功能:
<Suspense> 是一項(xiàng)實(shí)驗(yàn)性功能。它不一定會(huì)最終成為穩(wěn)定功能,并且在穩(wěn)定之前相關(guān) API 也可能會(huì)發(fā)生變化。
<Suspense> 是一個(gè)內(nèi)置組件,用來(lái)在組件樹(shù)中協(xié)調(diào)對(duì)異步依賴的處理。它讓我們可以在組件樹(shù)上層等待下層的多個(gè)嵌套異步依賴項(xiàng)解析完成,并可以在等待時(shí)渲染一個(gè)加載狀態(tài)。

意思就是此組件用來(lái)等待異步組件時(shí)渲染一些額外內(nèi)容,讓應(yīng)用有更好的用戶體驗(yàn)

要了解 <Suspense> 所解決的問(wèn)題和它是如何與異步依賴進(jìn)行交互的,我們需要想象這樣一種組件層級(jí)結(jié)構(gòu):

<Suspense>
└─ <Dashboard>
   ├─ <Profile>
   │  └─ <FriendStatus>(組件有異步的 setup())
   └─ <Content>
      ├─ <ActivityFeed> (異步組件)
      └─ <Stats>(異步組件)

在這個(gè)組件樹(shù)中有多個(gè)嵌套組件,要渲染出它們,首先得解析一些異步資源。如果沒(méi)有 <Suspense>,則它們每個(gè)都需要處理自己的加載、報(bào)錯(cuò)和完成狀態(tài)。在最壞的情況下,我們可能會(huì)在頁(yè)面上看到三個(gè)旋轉(zhuǎn)的加載態(tài),在不同的時(shí)間顯示出內(nèi)容。

有了 <Suspense> 組件后,我們就可以在等待整個(gè)多層級(jí)組件樹(shù)中的各個(gè)異步依賴獲取結(jié)果時(shí),在頂層展示出加載中或加載失敗的狀態(tài)。

接下來(lái)看個(gè)簡(jiǎn)單的例子:

首先需要引入異步組件

import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))

簡(jiǎn)潔一些就是用組件實(shí)現(xiàn)異步的加載的這么一個(gè)效果

Home父組件代碼如下:

<template>
  <div class="home">
    <h3>我是Home組件</h3>
    <Suspense>
       <template #default>
        <Child />
      </template>
      <template v-slot:fallback>
        <h3>Loading...</h3>
      </template>
    </Suspense>
  </div>
</template>
 
<script >
// import Child from './components/Child'//靜態(tài)引入
import { defineAsyncComponent  } from "vue";
const Child = defineAsyncComponent(() => import("../components/Child"));
export default {
  name: "",
  components: { Child },
};
</script>
 
<style>
.home {
  width: 300px;
  background-color: gray;
  padding: 10px;
}
</style>

自組件Child

<template>
  <div class="child">
    <h3>我是Child組件</h3>
    name: {{user.name}}
    age: {{user.age}}
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  name: "Child",
  async setup() {
    const NanUser = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve({
            name: "NanChen",
            age: 20,
          });
        },2000);
      });
    };
    const user = await NanUser();
    return {
      user,
    };
  },
};
</script>

<style>
.child {
  background-color: skyblue;
  padding: 10px;
}
</style>

根據(jù)插槽機(jī)制,來(lái)區(qū)分組件, #default 插槽里面的內(nèi)容就是你需要渲染的異步組件; #fallback 就是你指定的加載中的靜態(tài)組件。

效果如下:
請(qǐng)?zhí)砑訄D片描述

到此這篇關(guān)于Vue3異步組件Suspense的使用方法詳解的文章就介紹到這了,更多相關(guān)Vue3異步組件Suspense的使用方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論