vue 实现数据懒加载
Vue 实现数据懒加载的方法
使用 Intersection Observer API
Intersection Observer API 可以检测元素是否进入视口,适合实现图片或内容的懒加载。
// 创建观察器实例
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const lazyElement = entry.target
lazyElement.src = lazyElement.dataset.src
observer.unobserve(lazyElement)
}
})
})
// 获取所有需要懒加载的元素
document.querySelectorAll('.lazy').forEach(element => {
observer.observe(element)
})
结合 Vue 指令实现
可以封装一个自定义指令,方便在 Vue 项目中复用。
// 注册全局指令
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 loaded image">
使用第三方库
Vue-lazyload 是一个流行的懒加载库,支持图片和组件懒加载。

安装:
npm install 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">
路由级别的懒加载
对于 Vue 路由组件,可以使用动态 import 实现懒加载。
const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
列表数据懒加载
对于长列表,可以监听滚动事件实现分页加载。
methods: {
loadMore() {
if (this.isLoading || !this.hasMore) return
this.isLoading = true
fetchData().then(data => {
this.items.push(...data)
this.hasMore = data.length > 0
this.isLoading = false
})
}
},
mounted() {
window.addEventListener('scroll', () => {
const { scrollTop, clientHeight, scrollHeight } = document.documentElement
if (scrollTop + clientHeight >= scrollHeight - 100) {
this.loadMore()
}
})
}
注意事项
- 懒加载图片时应该设置占位图,避免布局抖动
- 对于 SEO 重要的内容,不建议使用懒加载
- 移动端需要考虑网络状况,适当提前加载
- 使用 Intersection Observer 时注意浏览器兼容性
这些方法可以根据具体场景组合使用,实现最佳的用户体验和性能优化。






