vue 实现图片懒加载
Vue 图片懒加载实现方法
使用 Intersection Observer API
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="description">
使用第三方库 vue-lazyload
对于需要更复杂功能或兼容旧浏览器的场景,可以使用成熟的第三方库。

安装依赖:

npm install vue-lazyload
配置使用:
import VueLazyload from 'vue-lazyload'
const app = createApp(App)
app.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 3
})
// 模板使用
<img v-lazy="imageUrl" alt="description">
自定义滚动事件监听
对于需要兼容老版本浏览器的场景,可以通过监听滚动事件实现。
const lazyLoad = {
mounted(el, binding) {
function loadImage() {
const rect = el.getBoundingClientRect()
if (rect.top < window.innerHeight + 100) {
el.src = binding.value
window.removeEventListener('scroll', loadImage)
}
}
window.addEventListener('scroll', loadImage)
loadImage() // 初始检查
}
}
注意事项
- 图片元素应设置初始占位图或背景色避免布局抖动
- 考虑设置合适的 rootMargin 提前加载可视区域附近的图片
- 移动端需要特别处理 touch 事件确保流畅体验
- 对于 SSR 应用需要区分客户端和服务端环境
以上方法可根据项目需求选择,现代项目推荐优先使用 Intersection Observer API 方案。






