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 来模拟异步加载数据,渲染成功与失败的页面效果

<!-- -->
<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: "参数错误" });
      }
      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加载异步数据的使用

请求 返回数据时候

vue3之Suspense加载异步数据的使用

请求 返回错误时候

vue3之Suspense加载异步数据的使用

原文地址:https://blog.csdn.net/weixin_43845137/article/details/127836913

相关文章:

  • 2022-12-23
  • 2021-06-23
  • 2021-06-27
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
猜你喜欢
  • 2022-12-28
  • 2023-01-26
  • 2021-09-30
  • 2021-07-10
  • 2021-11-13
  • 2021-09-14
相关资源
相似解决方案