vue3封装自定义指令 实现图片懒加载

vue3封装自定义指令 实现图片懒加载

主要使用的api:

IntersectionObserver

// 创建观察对象实例
// const observer = new IntersectionObserver(callback[, options])

const obs = new IntersectionObserver(([{isIntersecting}], observer) => {
    // entries = [{isIntersecting: true}]
    
}, {})
// 监听DOM元素
obs.observe(imgDom)
// 取消DOM监听
obs.unobserve(imgDom)

// callback 被观察dom进入可视区离开可视区都会触发
// - 两个回调参数 entries , observer
// - entries 被观察的元素信息对象的数组 [{元素信息},{}],信息中isIntersecting判断进入或离开
// - observer 就是观察实例
// options 配置参数
// - 三个配置属性 root rootMargin threshold
// - root 基于的滚动容器,默认是document
// - rootMargin 容器有没有外边距
// - threshold 交叉的比例

// 实例提供两个方法
// observe(dom) 观察哪个dom
// unobserve(dom) 停止观察那个dom

实现代码

import defaultImg from '@/assets/images/200.png'
// 指令
const defineDirective = (app) => {
  // 图片懒加载指令
  app.directive('lazyload', {
    mounted (el, binding) {
 //el 表示使用指令的dom元素 bindings表示指令的相关信息
 // 监听图片进入了可视区       
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
          //进入可视区 
        if (isIntersecting) {
            //取消图片的监听
          observer.unobserve(el)
            //加载图片失败 显示默认的图片地址
          el.onerror = () => {
              el.src = defaultImg
          } 
          //给图片的src属性赋值图片地址
          el.src = binding.value
        }
      }, {
        threshold: 0.01
      })
      observer.observe(el)
    }
  })
}
//注册插件
export default {
  install (app) {
  defineDirective(app)
  }
}

使用

<img alt="" v-lazyload="cate.picture">
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值