溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

vue3之Suspense加載異步數(shù)據(jù)怎么使用

發(fā)布時間:2023-02-07 09:31:53 來源:億速云 閱讀:148 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了vue3之Suspense加載異步數(shù)據(jù)怎么使用的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇vue3之Suspense加載異步數(shù)據(jù)怎么使用文章都會有所收獲,下面我們一起來看看吧。

Suspense使用

<template>
  <Suspense>
    <template #default>
      <ProductList></ProductList>
    </template>
    <template #fallback> <div>loading...</div> </template>
  </Suspense>
</template>

<script setup lang="ts" name="Cart">
import ProductList from "./ProductList.vue";
</script>
<style lang="scss" scoped></style>

組件

使用 flag 與 Promise 來模擬異步加載數(shù)據(jù),渲染成功與失敗的頁面效果

<!-- -->
<template>
  <div v-if="data">
    ProductList
    <div>data父 - {{ data }}</div>
  </div>
  <div v-if="err">
    {{ err }}
  </div>
</template>

<script setup lang="ts" name="ProductList">
import { ref } from "vue";

const data = ref<any>(null);
const flag = false;
const err = ref(null);
function aaa() {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (!flag) {
        return resolve({ code: 0, errorMsg: "參數(shù)錯誤" });
      }
      return resolve({
        code: 200,
        data: {
          result: 42,
        },
      });
    }, 3000);
  });
}
const res = await aaa();
console.log(res);

if (res.code === 200) {
  data.value = res.data.result;
} else {
  data.value = "";
  err.value = res.errorMsg;
}
</script>
<style lang="scss" scoped></style>

效果

調用請求的 loading效果

vue3之Suspense加載異步數(shù)據(jù)怎么使用

請求 返回數(shù)據(jù)時候

vue3之Suspense加載異步數(shù)據(jù)怎么使用

請求 返回錯誤時候

vue3之Suspense加載異步數(shù)據(jù)怎么使用

關于“vue3之Suspense加載異步數(shù)據(jù)怎么使用”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“vue3之Suspense加載異步數(shù)據(jù)怎么使用”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI