发布于 2026-01-06 15 阅读
0

Vue 3 中的组件懒加载

Vue 3 中的组件懒加载

快速加载速度对于任何Web应用程序的开发都至关重要。哪怕仅仅几秒钟的延迟,都可能对网站访问量产生巨大影响。这意味着,拥有一个快速的网站不仅对提升谷歌搜索排名至关重要,而且对吸引用户与网页互动也同样重要。

Vue 3 引入了多项新特性,通过改进异步组件 API 和新增的 Suspense 组件,帮助您轻松实现这一目标。本文将探讨如何在 Vue 3 中使用懒加载组件来加快页面加载速度。


请观看本文所对应的 YouTube 视频:

替代文字


在这个示例应用中,我们有一个SecretImage组件,它仅在用户通过身份验证后才会显示 Vue 徽标的交互式图形。为了防止未经授权的用户看到我们最重要的资产,我们添加了一个按钮来切换该组件的可见性。



<template>
  <!-- ... -->
  <!-- Large component that uses many libraries -->
  <SecretImage v-if="isLoggedIn" />
  <!-- ... -->
</template>

<script>
import SecretImage from './components/SecretImage.vue'

export default {
  components: { SecretImage }
  // ...
}
</script>


Enter fullscreen mode Exit fullscreen mode

在开发过程中,SecretImage我们使用了许多复杂的库,导致 JavaScript 代码量增加。我们可以看到,构建应用程序时会生成一个庞大的 vendor 文件,该文件会在我们首次向网站发出请求时加载。

替代文字

异步组件

我们可以使用defineAsynComponentVue 3 新增的功能。我们只需要传递一个加载组件的函数即可。由于 Vue 已经预配置了 webpack,我们可以使用动态导入功能。



<template>
  <!-- ... -->
  <SecretImage v-if="isLoggedIn" />
  <!-- ... -->
</template>

<script>
import { defineAsyncComponent } from 'vue'
const SecretImage = defineAsyncComponent(() =>
  import('./components/SecretImage.vue')
)

export default {
  components: { SecretImage }
  // ...
}
</script>


Enter fullscreen mode Exit fullscreen mode

现在当我们构建应用程序时,可以看到已经创建了一个新文件,并且 vendor 文件已显著减少。

替代文字

重新登录后,我们还可以看到正在创建一个新的请求来加载我们的SecertImage组件。

由于该组件稍后加载,因此在请求和渲染 UI 的延迟加载部分时可能会有短暂的延迟。我们还可以传入一个加载组件属性,该属性将在组件加载时显示。



import { defineAsyncComponent } from 'vue'
import Loading from './components/Loading.vue'

const SecretImage = defineAsyncComponent({
  loader: () => import('./components/SecretImage.vue'),
  loadingComponent: Loading
})


Enter fullscreen mode Exit fullscreen mode

但是,使用这种方法可能会有局限性,因为很难将 props 或 slot 传递给加载组件。

悬念

为了增加灵活性,我们可以使用新Suspense组件,它允许我们在模板中以组件的形式实现异步加载内容。我们只需调用该Suspense组件,并为默认插槽和备用插槽分别传入一个组件即可。



<template>
  <!-- ... -->
  <Suspense v-if="isLoggedIn">
    <template #default>
       <SecretImage />
    </template>
    <template #fallback>
       <Loading />
    </template> 
  </Suspense>
  <SecretImage v-if="isLoggedIn" />
  <!-- ... -->
</template>

<script>
import { defineAsyncComponent } from 'vue'
import Loading from './components/Loading.vue'

const SecretImage = defineAsyncComponent(() =>
  import('./components/SecretImage.vue')
)

export default {
  components: { SecretImage, Loading  }
  // ...
}
</script>


Enter fullscreen mode Exit fullscreen mode

默认槽位在异步内容加载完毕后显示,备用槽位在状态加载时显示。


感谢阅读!如果你喜欢我的帖子,别忘了关注我并订阅我的YouTube频道!

文章来源:https://dev.to/jsbroks/lazy-loading-components-in-vue-3-21o7