图片的懒加载功能是通过IntersectionObserver来实现的。
以下是封装的组件
<template>
<div>
<img :src="placeholderImage" alt="" :data-src="src" ref="LazyImg" />
</div>
</template>
<script>
export default {
props: {
src: {
type: String,
require: true
}
},
data() {
return {
placeholderImage: ''
}
},
mounted() {
this.Lazy()
},
methods: {
Lazy() {
const image = this.$refs.LazyImg
const observe = new IntersectionObserver((el) => {
el.forEach((element) => {
// isIntersecting是 是否进入可视区 true
// 判断进入可视区时,将被观察的targe 的值img
// 当在HTML中使用data-前缀定义自定义数据属性时,
// 可以通过dataset属性访问这些属性的值。
// 当进入可视区时 将自定义的数据 dataset 赋给src
if (element.isIntersecting) {
const img = element.target
img.src = img.dataset.src
// 离开可视区时 停止监听
observe.unobserve(img)
}
})
})
// 开始监听
observe.observe(image)
}
}
}
</script>
使用懒加载组件的话
<LazyImg :src="item.pic" alt=""></LazyImg>
没有封装的原生懒加载
<img :src="placeholderImage" :data-src="item.pic" alt="" ref="lazyImage" />
lazyLoadImages() {
const images = this.$refs.lazyImage
const observer = new IntersectionObserver((el) => {
el.forEach((element) => {
// isIntersecting 表示这个元素进入可视区是true
if (element.isIntersecting) {
// target 表示的是被观察的元素
const img = element.target
console.log(img, '222')
// 当在HTML中使用data-前缀定义自定义数据属性时,
// 可以通过dataset属性访问这些属性的值。
// 例如,如果在img元素上定义了data-src属性,可以通过img.dataset.src来获取该属性的值。
img.src = img.dataset.src
// unobserve表示停止监听
observer.unobserve(img)
}
})
})
images.forEach((img) => {
observer.observe(img)
})
// console.log(observer)
}