前置知识: Vue 3

异步组件与Suspense

00:00
1 min Advanced 2026/6/14

Vue 3异步组件defineAsyncComponent与Suspense配合使用。

1. defineAsyncComponent

1.1 基本用法

const AsyncComp = defineAsyncComponent(() => import('./components/HeavyComponent.vue'));

1.2 完整配置

const AsyncComp = defineAsyncComponent({
  loader: () => import('./HeavyComponent.vue'),
  loadingComponent: LoadingSpinner,
  errorComponent: ErrorDisplay,
  delay: 200, // 延迟显示 loading
  timeout: 3000, // 超时显示 error
  suspensible: false, // 不与 Suspense 配合
  onError(error, retry, fail, attempts) {
    if (attempts <= 3) retry();
    else fail();
  },
});

2. Suspense

2.1 基本用法

<Suspense>
  <template #default>
    <AsyncComponent />
  </template>
  <template #fallback>
    <LoadingSpinner />
  </template>
</Suspense>

2.2 配合 async setup

// 子组件
export default {
  async setup() {
    const data = await fetchData(); // Suspense 等待此 Promise
    return { data };
  },
};

2.3 事件处理

const suspenseRef = ref();

suspenseRef.value?.onPending();
suspenseRef.value?.onResolve();
suspenseRef.value?.onFallback();

Suspense 仍是实验性功能,API 可能变更

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式