IntersectionObserver API 创建图片懒加载(实战)

本文介绍了如何使用 Vue.js 实现一个图片懒加载组件,通过 Intersection Observer API 监听元素进入视口时动态替换 src 属性,提高页面性能。关键点包括模板结构、TypeScript编写、以及使用 Intersection Observer 错误处理和交互监听。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、 效果图

在这里插入图片描述

二、 代码

<template>
  <img
    ref="imgLazy"
    :data-src="dataSrc"
    :src="src"
    :alt="alt"
    :title="title"
    class="kh-img-lazy"
    @error="imgErrorHandle"
  >
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';

export default defineComponent({
  name: 'KhImgLazy',
  props: {
    dataSrc: {
      type: String,
      default: ''
    },
    alt: {
      type: String,
      default: 'img'
    },
    title: {
      type: String,
      default: ''
    }
  },
  setup() {
    const IMG_LAZY = reactive({
      error: require('@client/assets/imgs/common/kh_error.webp'),
      src: require('@client/assets/imgs/common/kh_loading.webp'),
      io: ref<any>(null),
    })

    return {
      ...toRefs(IMG_LAZY)
    }
  },
  watch: {
    dataSrc: {
      deep: true,
      handler: function() {
        this.listenIntersection();
      }
    }
  },
  mounted() {
    this.listenIntersection();
  },
  methods: {

    /**
     * @description imgErrorHandle img 错误处理函数
     * @returns { void }
     */
    imgErrorHandle(): void {
      this.src = this.error; // img error
    },

    /**
     * @description listenIntersection 监听交互事件
     * @returns { void }
     */
    listenIntersection(): void {
      this.io = new IntersectionObserver((entries) => {
        entries.forEach((val) => {
          if (val && val.isIntersecting && val.target) {
            this.src = this.dataSrc; // 赋值img src属性

            // 取消监听
            this.io.unobserve(this.$refs.imgLazy as HTMLBaseElement);
            this.io = null;
          }
        })
      })

      // 监听 img
      this.io.observe(this.$refs.imgLazy as HTMLBaseElement)
    }
  }
});
</script>

<style lang="less" scoped>
/** define kh-img-lazy */
.kh-img-lazy {
  width: auto;
  max-width: 100%;
}
</style>

三、源码下载

github地址
记得star(哈哈)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kinghiee

助力蛋白粉计划

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值