vue实现页面懒加载
Vue 实现页面懒加载的方法
Vue 提供了多种方式实现页面或组件的懒加载,主要目的是优化应用性能,减少初始加载时间。以下是几种常见的实现方法:
使用 Vue Router 的懒加载
在路由配置中,通过动态导入语法实现组件懒加载。当访问对应路由时,组件才会被加载。
const routes = [
{
path: '/lazy-component',
component: () => import('./components/LazyComponent.vue')
}
]
使用 Vue 的异步组件
在组件注册时使用动态导入,实现按需加载。这种方式适合非路由组件。

const AsyncComponent = () => ({
component: import('./components/AsyncComponent.vue'),
loading: LoadingComponent, // 可选加载状态组件
error: ErrorComponent, // 可选错误状态组件
delay: 200, // 延迟显示加载组件
timeout: 3000 // 超时时间
})
export default {
components: {
'async-component': AsyncComponent
}
}
结合 Suspense 组件(Vue 3)
Vue 3 的 Suspense 组件可以更好地处理异步组件加载状态。
<template>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<div>Loading...</div>
</template>
</Suspense>
</template>
<script>
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
export default {
components: {
AsyncComponent
}
}
</script>
图片懒加载

对于图片资源,可以使用 Intersection Observer API 或第三方库实现懒加载。
<template>
<img v-lazy="imageUrl" alt="Lazy loaded image">
</template>
<script>
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
})
</script>
动态导入结合 Webpack 代码分割
通过 Webpack 的魔法注释可以更好地控制代码分割。
const LazyComponent = () => import(
/* webpackChunkName: "lazy-component" */
'./components/LazyComponent.vue'
)
这些方法可以根据具体场景选择使用,路由懒加载适合页面级组件,异步组件适合局部功能模块,图片懒加载则针对媒体资源优化。






