vue图片实现懒加载
vue图片实现懒加载的方法
使用Intersection Observer API
Intersection Observer API是现代浏览器提供的原生API,可以高效检测元素是否进入视口。

// 创建观察器实例
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
observer.unobserve(img)
}
})
})
// 在Vue组件中使用
mounted() {
const images = document.querySelectorAll('[data-src]')
images.forEach(img => observer.observe(img))
}
使用vue-lazyload插件
vue-lazyload是专门为Vue设计的懒加载插件,使用简单且功能丰富。

npm install vue-lazyload -S
// main.js中配置
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 3
})
// 组件中使用
<img v-lazy="imageUrl">
自定义指令实现
可以创建自定义指令来实现懒加载功能。
// 注册全局指令
Vue.directive('lazy', {
inserted: (el, binding) => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
observer.observe(el)
}
})
// 使用方式
<img v-lazy="imageUrl">
兼容性处理
对于不支持Intersection Observer的旧浏览器,可以添加polyfill或回退方案。
// 引入polyfill
import 'intersection-observer'
// 或使用scroll事件作为fallback
function lazyLoadFallback() {
const images = document.querySelectorAll('[data-src]')
images.forEach(img => {
const rect = img.getBoundingClientRect()
if (rect.top < window.innerHeight && rect.bottom >= 0) {
img.src = img.dataset.src
}
})
}
window.addEventListener('scroll', lazyLoadFallback)
性能优化建议
- 为懒加载图片设置占位图
- 合理设置preLoad参数
- 对滚动事件进行节流处理
- 考虑使用低质量图片占位(LQIP)技术
- 对于大量图片考虑虚拟滚动方案
以上方法可以根据项目需求选择使用,现代Vue项目推荐使用vue-lazyload插件,它提供了更多高级功能和更好的兼容性处理。






