1)定义懒加载全局指令插件 ------------------------ `scr/directives/index.js`
export default {
install (app) {
// 定义全局指令
}
}
2)main.js中注册插件
import defineDirective from '@/directives'
createApp(App).use(defineDirective).mount('#app')
3)图片懒加载指令逻辑 ------------------------ `scr/directives/index.js`
核心思路:监听图片是否进入到视口,正式进入视口之后将图片url数据交给img标签的src属性
import defaltImg from '@/assets/images/200.png'
// 引入监听是否进入视口
import { useIntersectionObserver } from '@vueuse/core'
export default {
// 需要拿到main.js中由createApp方法产出的app实例对象
install (app) {
// app实例身上有我们想要的全局注册指令方法 调用即可
app.directive('imgLazy', {
mounted (el, binding) {
// el:img dom对象
// binding.value 图片url地址
// 使用vueuse/core提供的监听api 对图片dom进行监听 正式进入视口才加载
// img.src = url
console.log(el, binding)
const { stop } = useIntersectionObserver(
// 监听目标元素
el,
([{ isIntersecting }], observerElement) => {
if (isIntersecting) {
// 当图片url无效加载失败的时候使用默认图片替代
el.onerror = function () {
el.src = defaltImg
}
el.src = binding.value
stop()
}
},
// 刚进入视口区域就立刻执行回调 0 - 1
{ threshold: 0 }
)
}
})
}
}
4)测试使用 --------------`home-product.vue`
<img v-imgLazy="i.picture" alt="">