Vue3学习记录——(7) 异步加载defineAsyncComponent与Suspense组件

一、defineAsyncComponent

1、用法一
<template>
  <div>
    <AsyncComp />
  </div>
</template>

<script setup lang="ts">

import { Component, defineAsyncComponent } from 'vue';
const AsyncComp = defineAsyncComponent<Component>(() => import("@/components/HelloWorld.vue"))

</script>
1、用法二
<template>
  <div>
    <AsyncComp />
  </div>
</template>

<script setup lang="ts">
import { Component, defineAsyncComponent } from 'vue';
import Loading from "@/components/Loading.vue"
import Error from "@/components/Error.vue"

const AsyncComp = defineAsyncComponent<Component>({
  /* 延迟3秒后加载组件 */
  loader: () => (
    new Promise(r => {
      setTimeout(() => r(import("./AboutView.vue")), 3000)
    })
  ),
  /* 加载中展示的组件 */
  loadingComponent: Loading,
  /* 加载失败展示的组件 */
  errorComponent: Error,
  /* 在展示加载中组件之前的延时(毫秒) */
  delay: 200,
  /* 设置加载超时时间(注:超时后加载的组件还是会加载出来) */
  timeout: 1000,
  /* 异常回调 error-异常信息 retry-重试函数 fail-终止函数 attempts-重试次数 */
  onError(error, retry, fail, attempts) {},
})
</script>

二、Suspense

<template>
  <Suspense>
  	//要加载的组件
    <component :is="asyncComp" />
    //加载中展示的组件
    <template #fallback>
      <div>加载中...</div>
    </template>
  </Suspense>
</template>

<script setup lang="ts">
import { Component, defineAsyncComponent } from 'vue';

//模拟创建一个3秒延时的异步组件
const asyncComp = defineAsyncComponent<Component>(() => (
  new Promise(r => {
    setTimeout(() => {
      r(import("@/components/HelloWorld.vue"))
    }, 3000);
  })
))

</script>

你可能感兴趣的:(Vue3学习记录,学习,vue.js,前端)