Vue3如何优雅的加载图片

本文介绍了如何在Vue应用中使用IntersectionObserverAPI实现图片的懒加载功能,以提升页面性能。通过监测元素可见性,只有当图片进入视口时才实际加载,同时提供了过渡动画效果。

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

页面首页会加载大量的图片,初次进入页面时,会导致页面性能下降,于是乎,改进这个功能,可以让所有图片自动懒加载
这个功能主要的底层逻辑是是使用IntersectionObserver API,IntersectionObserver用于在浏览器中观察元素的可见性和位置变化。它可以帮助开发者实现一些动态行为,如图片的懒加载、无限滚动等

// 创建IntersectionObserver实例

const observer = new IntersectionObserver((entries, observer) => {

    // 遍历元素观察对象
    entries.forEach(entry => {
        if (entry.isIntersecting) {

            // 加载图片
            const img = entry.target;
            const src = img.getAttribute('data-src');
            img.setAttribute('src', src);
            img.onload = () => {
               img.setAttribute('class', `${props.imgClass} fade-in`);
            }
             // 停止观察元素
            observer.unobserve(img)
        }
    })
});

// 获取所有需要懒加载的图片元素
const lazyImages = documents.querySelectorAll('.lazy-image');

// 观察每个图片元素
lazyImages.forEach(image => {
    observer.observe(image);
});

接下来实现一个通用的 组件,基本的功能如下:
1.给图片提供默认的占位图片 src,同时提供data-src属性
2.传入图片对应的 ref 属性。
3.当图片进入可视区域时,使用data-src属性替换 src 属性

import { ref, onMounted } from 'vue';

const options = {
  root: document.getElementById(`${props.rootId}`),
  rootMargin: "0px", // 根元素的边距离
  threshold: 0.5 // 可见性比例阈值
};

const callback = (entries, observer) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      const src = img.getAttribute('data-src');
      img.setAttribute('src', src); // 将真是的图片地址付给src属性
      img.onload = () => {
        img.setAttribute('class', `${props.imgClass} fade-in`);
      }
      observer.unobserve(img)
    }
  });
}
<div :class="props.wrapClass" v-viewer="{ toolbar: false }">
    <template v-for="imgSrc of props.dataSource" :key="imgSrc">
      <img ref="imgRef" :class="imgClass" :data-src="imgSrc"/>
    </template>
</div>

接下来,我们增加个过渡动画。每次当加载完图片,就从占位图过渡到正常图片模式。

img.onload = () => {
    img.setAttribute('class', `${props.imgClass} fade-in`);
}
@keyframes fadeIn  {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.fade-in {
  animation: fadeIn 0.6s ease-in;
}

完整示例代码

<template>
  <div :class="props.wrapClass" v-viewer="{ toolbar: false }">
    <template v-for="imgSrc of props.dataSource" :key="imgSrc">
      <img ref="imgRef" :class="imgClass" :data-src="imgSrc"/>
    </template>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';

const props = defineProps({
  dataSource: {
    type: Array,
    default: () => []
  },
  wrapClass: {
    type: String,
    default: ''
  },
  imgClass: {
    type: String,
    default: ''
  },
  rootId: {
    type: String,
    default: ''
  }
});
const options = {
  root: document.getElementById(`${props.rootId}`),
  rootMargin: "0px",
  threshold: 0.5
};
const callback = (entries, observer) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      const src = img.getAttribute('data-src');
      img.setAttribute('src', src);
      img.onload = () => {
        img.setAttribute('class', `${props.imgClass} fade-in`);
      }
      observer.unobserve(img)
    }
  });
}
const imgRef = ref(null);
onMounted(() => {
  const observer = new IntersectionObserver(callback, options);
  Object.keys(imgRef.value).forEach(item => {
    observer.observe(imgRef.value[item]);
  });
});
</script>
<style scoped lang="less">
@keyframes fadeIn  {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.fade-in {
  animation: fadeIn 0.6s ease-in;
}
</style>

参考资料
https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值