1、使用new IntersectionObserver()实现图片懒加载,配合指令v-directive
const imgLazy = {
mounted(el) {
const imgSrc = el.src
el.src = ''
const IntersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
console.log('不可见')
return
}
console.log('可见')
el.src = imgSrc
})
IntersectionObserver.observe(el)
}
}
/**
* app.use(xxx) 相当于调用插件xxx,调用时会调用install方法,install方法中会传入app对象
*/
export default {
install: (app) => {
app.directives('imgLazy', imgLazy)
}
}
2、使用vueuse的useIntersectionObserver 实现图片的懒加载
ps:useIntersectionObserver
import { useIntersectionObserver } from '@vueuse/core'
const imgLazy = {
mounted(el) {
const imgSrc = el.src
el.src = ''
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = imgSrc
stop()
}
})
}
}
/**
* app.use(xxx) 相当于调用插件xxx,调用时会调用install方法,install方法中会传入app对象
*/
export default {
install: (app) => {
app.directives('imgLazy', imgLazy)
}
}