Vue3中如何注册自定义指令实现图片懒加载

266 阅读1分钟

在Vue三种如何用自定义指令实现图片懒加载.与Vue2中不同的是Vue3中组测自定义指令有七个钩子函数而Vue2中只有五个


// 创建观察对象实例
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
install (Vue) {
Vue.directive('lazy', {
      mounted (el, binding) {
        // 浏览器提供 IntersectionObserver
        const observer = new IntersectionObserver(
          ([{ isIntersecting }]) => {
            // console.log(isIntersecting, '====IntersectionObserver')
            if (isIntersecting) {
              // 图片加载失败就显示默认图片
              el.onerror = function () {
                el.src = defaultImg
              }
              el.src = binding.value
              // 不在监听dom===stop()
              observer.unobserve(el)
            }
          },
          {
            threshold: 0.01
          }
        )
        // 监听dom
        observer.observe(el)
      }
    })
    }