vue图片实现懒加载
vue图片实现懒加载的方法
使用Intersection Observer API
Intersection Observer API可以检测元素是否进入视口,适合实现懒加载。创建一个自定义指令或组件来监听图片是否进入可视区域。
// 自定义指令
Vue.directive('lazy', {
inserted: (el, binding) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
})
observer.observe(el)
}
})
在模板中使用:
<img v-lazy="imageUrl" alt="lazy image">
使用vue-lazyload插件
vue-lazyload是一个成熟的Vue懒加载插件,支持图片、背景图等资源的懒加载。
安装插件:

npm install vue-lazyload
在main.js中配置:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
})
在组件中使用:

<img v-lazy="imageUrl" alt="lazy image">
使用loading和error占位图
为提升用户体验,可以设置加载中和加载失败的占位图。
Vue.use(VueLazyload, {
loading: require('@/assets/loading.gif'),
error: require('@/assets/error.png')
})
监听滚动事件实现懒加载
对于不支持Intersection Observer的旧浏览器,可以通过监听滚动事件实现。
methods: {
handleScroll() {
const images = document.querySelectorAll('[data-src]')
images.forEach(img => {
if (img.getBoundingClientRect().top < window.innerHeight) {
img.src = img.dataset.src
img.removeAttribute('data-src')
}
})
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
this.handleScroll()
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
模板中使用data-src属性:
<img data-src="imageUrl" alt="lazy image">
注意事项
- 对于大量图片,使用Intersection Observer性能更好
- 移动端需要考虑网络环境,可以预加载更多图片
- 服务器端渲染(SSR)时需要注意懒加载的兼容性
- 可以结合webp等现代图片格式进一步优化性能






