vue懒加载实现方式
Vue 懒加载实现方式
路由懒加载
通过动态导入语法实现路由组件按需加载,减少首屏加载时间。
const routes = [
{
path: '/home',
component: () => import('./views/Home.vue')
},
{
path: '/about',
component: () => import('./views/About.vue')
}
]
Webpack 会将动态导入的组件打包成单独的文件,在访问对应路由时才会加载。
组件懒加载
使用 Vue 的 defineAsyncComponent 方法实现组件懒加载。
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
在模板中像普通组件一样使用:
<template>
<AsyncComponent />
</template>
图片懒加载
通过 v-lazy 指令或 Intersection Observer API 实现图片懒加载。

使用 vue-lazyload 插件:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
})
在模板中使用:
<img v-lazy="imageUrl" />
懒加载指令
自定义懒加载指令,基于 Intersection Observer API。

const lazyLoad = {
mounted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
})
observer.observe(el)
}
}
app.directive('lazy', lazyLoad)
使用方式:
<img v-lazy="imageUrl" alt="Lazy loaded image">
懒加载库
使用第三方库如 lozad.js 实现更复杂的懒加载需求。
import lozad from 'lozad'
const observer = lozad('.lazy', {
loaded: function(el) {
el.classList.add('loaded')
}
})
observer.observe()
HTML 中使用:
<img class="lazy" data-src="image.jpg">
注意事项
- 懒加载可能影响 SEO,需确保搜索引擎能正确抓取内容
- 考虑设置合理的预加载区域,避免用户等待
- 对关键内容谨慎使用懒加载,保证用户体验
- 移动端网络环境较差时,懒加载效果更明显
以上方法可根据实际需求组合使用,平衡性能和用户体验。






