HTML代码
<ul class="imgs_list">
<li v-for="(item, i) in imgsData" :key="i">
<img v-lazyload="item">
</li>
</ul>
注册全局自定义指定v-lazyload
// 当前代码卸载main.js中
Vue.directive('lazyload', {
bind: function (el, bindVal) {
const lazyLoadObser = new IntersectionObserver((entries, observer) => {
entries.forEach((entry, index) => {
const lazyImg = entry.target
// intersectionRatio:目标元素的可见比例,
// 即intersectionRect占boundingClientRect的比例,
// 完全可见时为1,完全不可见时小于等于0
if (entry.intersectionRatio > 0) {
lazyImg.src = bindVal.value
console.log(111)
lazyLoadObser.unobserve(lazyImg)
}
})
})
lazyLoadObser.observe(el)
}
})