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

创建一个名为 lazy-load.js 的自定义指令文件:

const LazyLoadDirective = {
  mounted(el, binding) {
    const options = binding.value || {};
    const { src, threshold = 0 } = options;

    let observer;

    function loadImage(entries, observer) {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          el.src = src;
          observer.unobserve(el);
        }
      });
    }

    observer = new IntersectionObserver(loadImage, {
      rootMargin: `${threshold}px 0px`,
    });
    observer.observe(el);
  },
};

export default LazyLoadDirective;

然后,在你的 Vue 应用中,全局注册这个自定义指令:

import { createApp } from 'vue';
import LazyLoadDirective from './directives/lazy-load';

const app = createApp(App);

app.directive('lazy-load', LazyLoadDirective);

app.mount('#app');

最后,在你的模板中使用这个自定义指令:

<img v-lazy-load="{ src: 'placeholder.jpg', threshold: 100 }" alt="Lazy Loaded Image">

这样,当图片进入视窗并达到指定的阈值时,它将开始加载真实的图片。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值