介绍一个webAPI:IntersectionObserver
// 创建观察对象实例
const observer = new IntersectionObserver(callback[, options])
// callback 被观察dom进入可视区离开可视区都会触发
// - 两个回调参数 entries , observer
// - entries 被观察的元素信息对象的数组 [{元素信息},{}],信息中isIntersecting判断进入或离开
// - observer 就是观察实例
// options 配置参数
// - 三个配置属性 root rootMargin threshold
// - root 基于的滚动容器,默认是document
// - rootMargin 容器有没有外边距
// - threshold 交叉的比例
// 实例提供两个方法
// observe(dom) 观察哪个dom
// unobserve(dom) 停止观察那个dom
基于vue3.0和IntersectionObserver封装懒加载指令
src/components/index.js
const requireComponent = require.context('./', true, /\.vue$/)
// 定义指令
const defineDirective = (app) => {
// 1. 图片懒加载指令 v-lazy
// 原理:先存储图片地址不能在src上,当图片进入可视区,将你存储图片地址设置给图片元素即可。
app.directive('lazy', {
// vue2.0 监听使用指令的DOM是否创建好,钩子函数:inserted
// vue3.0 的指令拥有的钩子函数和组件的一样,使用指令的DOM是否创建好,钩子函数:mounted
mounted (el, binding) {
// 2. 创建一个观察对象,来观察当前使用指令的元素
const observe = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
// 停止观察
observe.unobserve(el)
// 3. 把指令的值设置给el的src属性 binding.value就是指令的值
// 4. 处理图片加载失败 error 图片加载失败的事件 load 图片加载成功
el.onerror = () => {
// 加载失败,设置默认图
el.src = defaultImg
}
el.src = binding.value
}
}, {
threshold: 0
})
// 开启观察
observe.observe(el)
}
})
}
export default {
install (app) {
requireComponent.keys().forEach(path => {
// 导入组件
const component = requireComponent(path).default()
// 注册组件
app.component(component.name, component)
defineDirective(app)
})
}
}
组件中使用
<img v-lazyload="cate.picture" />
此外,使用@vueuse/core库也可以实现
import { useIntersectionObserver } from '@vueuse/core'
// 进入视区获取数据
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
if (isIntersecting) {
stop()
// 调用逻辑
...
}
}
)
app.directive('lazyload',{
mounted(el,binding)=>{
useIntersectionObserver(el,([{ isIntersecting }], observerElement)=>{
if(isIntersecting){
stop()
src.value = binding.value
}
})
}
})