异步组件

可将大型应用分割成小一些的代码块,减小主包体积,并且只在需要的时候才从服务器加载一个模块。。

所谓的异步组件就是通过import或者require导入的vue组件。 例如:const componentA = import('@/components/componentA.vue'); 或者 const componentA = require('@/components/componentA.vue'); 注: @/ 的意思是返回到根路径,如使用vue-cli创建的项目,则使用@/则返回到src目录下。 如果要访问最外层的public目录中的文件则直接使用 / 即可,不加 /public 。

vue2实现方式

工厂函数

// 全局注册
Vue.component('child1', function (resolve) {
  require(['./components/child1'], resolve)
})
 
// 局部注册
components: {
  Child1: function (resolve) {
    require(['./components/child1'], resolve)
  }
}

Promise

// 全局注册
Vue.component('child2', () => import('./components/child2'))
 
// 局部注册
components: {
  Child2: () => import('./components/child2')
}

高阶组件

可以处理异步组件的加载状态和错误状态

// 全局注册
Vue.component('child3', () => ({
    component: import('./components/child3.vue'),
    loading: {template: '<div>Loading</div>'},
    error: {template: '<div>error</div>'},
    delay: 200,
    timeout: 3000
  })
)
// 局部注册
components: {
  Child3: () => ({
    // 需要加载的组件 (应该是一个 `Promise` 对象)
    component: import('./components/child3.vue'),
    // 异步组件加载时使用的组件
    loading: {template: '<div>Loading</div>'},
    // 加载失败时使用的组件
    error: {template: '<div>error</div>'},
    // 展示加载时组件的延时时间。默认值是 200 (毫秒)
    delay: 200,
    // 如果提供了超时时间且组件加载也超时了,
    // 则使用加载失败时使用的组件。默认值是:`Infinity`
    timeout: 3000
  })
}

vue3实现方式

import { defineAsyncComponent } from 'vue'

// 简单用法
const ArticleList = defineAsyncComponent(() =>
  import('@/components/ArticleList.vue')
) 

高阶用法

const AsyncPopup = defineAsyncComponent({
  loader: () => import('./ArticleList.vue'),
  // 加载异步组件时使用的组件
  loadingComponent: LoadingComponent,
  // 加载失败时使用的组件
  errorComponent: ErrorComponent
  // 在显示加载组件之前延迟。默认值:200ms。
  delay: 1000,
  // 超过给定时间,则会显示错误组件。默认值:Infinity。
  timeout: 3000,
  // 加载状态是否由<suspend>控制
  suspensible: true,
  // 一个函数,该函数包含4个参数,分别是error、retry、fail和attempts,这4个参数分别是错误对象、重新加载的函数、加载程序结束的函数、已经重试的次数。
  onError: (error,retry,fail,attempts) => {}
}) 

异步组件默认就是suspensible的。这意味着如果组件关系链上有一个<Suspense>,那么这个异步组件就会被当作这个<Suspense>的一个异步依赖。在这种情况下,加载状态是由<Suspense>控制,而该组件自己的加载、报错、延时和超时等选项都将被忽略。

异步组件,也可以通过,在选项中指定suspensible: false,表明不用 Suspense 控制,并让组件始终自己控制其加载状态。

分包

在setup语法糖里可以直接使用 顶层await。代码会被编译为 async setup()

<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>

父组件引用子组件时,使用defineAsyncComponent加载异步配合import 函数模式便可以分包

<script setup lang="ts">
import { reactive, ref, markRaw, toRaw, defineAsyncComponent } from 'vue'
 
const Dialog = defineAsyncComponent(() => import('../../components/Dialog/index.vue'))
</script>

suspense

<suspense> 组件有两个插槽。它们都只接收一个直接子节点。default 插槽里的节点会尽可能展示出来。如果不能,则展示 fallback 插槽里的节点。

  <Suspense>
    <template #default>
        <Dialog>
            <template #default>
                <div>我在哪儿</div>
            </template>
        </Dialog>
    </template>

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

事件

除了pending事件之外,<Suspense>组件还有pending、resolve和fallback事件。

  • pending事件是在进入挂起状态时触发。
  • resolve事件是在default插槽完成获取新内容时触发。
  • fallback事件则是在fallback插槽展示时触发。 例如,可以使用这些事件在加载新组件时在之前的 DOM 最上层显示一个加载指示器。

和其他事件组合

我们常常会将<Suspense>和<Transition>、<KeepAlive>等组件结合。要保证这些组件都能正常工作,嵌套的顺序非常重要。

另外,这些组件都通常与 Vue Router 中的<RouterView>组件结合使用。

下面的示例展示了如何嵌套这些组件,使它们都能按照预期的方式运行。若想组合得更简单,你也可以删除一些你不需要的组件:

<RouterView v-slot="{ Component }">
  <template v-if="Component">
    <Transition mode="out-in">
      <KeepAlive>
        <Suspense>
          <!-- 主要内容 -->
          <component :is="Component"></component>

          <!-- 加载中状态 -->
          <template #fallback>
            正在加载...
          </template>
        </Suspense>
      </KeepAlive>
    </Transition>
  </template>
</RouterView>

Vue Router 使用动态导入对懒加载组件进行了内置支持。这些与异步组件不同,目前他们不会触发<Suspense>。但是,它们仍然可以有异步组件作为后代,这些组件可以照常触发<Suspense>。

参考文档open in new window

Last Updated:
Contributors: haizhiguang