Vue3如何优雅的加载大量图片🚀🚀🚀

简介: Vue3如何优雅的加载大量图片🚀🚀🚀

最近开发了一个功能,页面首页会加载大量的图片,初次进入页面时,会导致页面性能下降,

于是乎,我改进了这个功能,可以让所有图片自动懒加载。

🚀 原理

这个功能主要的底层逻辑是是使用IntersectionObserverAPIIntersectionObserver用于在浏览器中观察元素的可见性和位置变化。它可以帮助开发者实现一些动态行为,如图片的懒加载、无限滚动等。

简单的示例如下:

// 创建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);
      // 停止观察该元素
      observer.unobserve(img);
    }
  });
});
// 获取所有需要懒加载的图片元素
const lazyImages = document.querySelectorAll('.lazy-image');
// 观察每个图片元素
lazyImages.forEach(image => {
  observer.observe(image);
});

🚀 实践

接下来我们实现一个通用的 hook,基本的功能如下:

  1. 给图片提供默认的占位图片 src,同时提供data-src属性
  2. 传入图片对应的 ref 属性。
  3. 当图片进入可视区域时,使用data-src属性替换 src 属性
import { onMounted, Ref } from "vue";
const options = {
  // root: document.querySelector(".container"), // 根元素,默认为视口
  rootMargin: "0px", // 根元素的边距
  threshold: 0.5, // 可见性比例阈值
  once: true,
};
function callback(
  entries: IntersectionObserverEntry[],
  observer: IntersectionObserver
) {
  entries.forEach((entry) => {
    // 处理每个目标元素的可见性变化
    if (entry.intersectionRatio <= 0) return;
    const img: Element = entry.target;
    const src = img.getAttribute("data-src");
    img.setAttribute("src", src ?? ""); // 将真实的图片地址赋给 src 属性
    observer.unobserve(img);
  });
}
export const useInView = (ref: Ref) => {
  const observer = new IntersectionObserver(callback, options);
  onMounted(() => {
    Object.keys(ref.value).forEach((e) => observer.observe(ref.value[e]));
  });
};
<script setup lang="ts">
import { ref } from "vue";
import { useInView } from "./hooks/useInView";
const imgRef = ref(null);
useInView(imgRef);
</script>
<template>
  <h4>公众号:萌萌哒草头将军</h4>
  <div
    v-for="(_, idx) in new Array(200).fill(11)"
  >
    <img
      ref="imgRef"
      src="https://via.placeholder.com/200"
      :data-src="`https://picsum.photos/200/${180 + idx}`"
      alt="b"
    />
  </div>
</template>

实际效果如下

image.png

虽然基本的功能要求已经完成了,但是现在还不够优雅!!!

🚀 优化

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

img.onload = () => {
  img.setAttribute('class', 'fade-in')
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
/* 应用淡入动画到元素 */
.fade-in {
  animation: fadeIn 0.6s ease-in;
}

完整代码如下:

import { onMounted, Ref } from "vue";
const options = {
  // root: document.querySelector(".container"), // 根元素,默认为视口
  rootMargin: "0px", // 根元素的边距
  threshold: 0.5, // 可见性比例阈值
  once: true,
};
function callback(
  entries: IntersectionObserverEntry[],
  observer: IntersectionObserver
) {
  entries.forEach((entry) => {
    if (entry.intersectionRatio <= 0) return;
    const img = entry.target as HTMLImageElement;
    const src = img.getAttribute("data-src");
    img.setAttribute("src", src ?? ""); // 将真实的图片地址赋给 src 属性
    img.onload = () => {
      img.setAttribute("class", "fade-in");
    };
    observer.unobserve(img);
  });
}
export const useInView = (ref: Ref) => {
  const observer = new IntersectionObserver(
    callback,
    options
  );
  onMounted(() => {
    Object.keys(ref.value)
      .forEach((e) => observer.observe(ref.value[e]));
  });
};
<script setup lang="ts">
import { ref } from "vue";
import { useInView } from "./hooks/useInView";
const imgRef = ref(null);
useInView(imgRef);
</script>
<template>
  <h4>公众号:萌萌哒草头将军</h4>
  <div
    v-for="(_, idx) in new Array(200).fill(11)"
    style="width: 200px height: 200px;"
  >
    <img
      ref="imgRef"
      style="height: 100%"
      src="https://via.placeholder.com/200"
      :data-src="`https://picsum.photos/200/${180 + idx}`"
      alt="b"
    />
  </div>
</template>
<style scoped>
/* 定义淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
/* 应用淡入动画到元素 */
.fade-in {
  animation: fadeIn 0.6s ease-in;
}
</style>
相关文章
|
3天前
|
JavaScript 容器
乾坤qiankun框架搭建 主应用为vue3的项目。
乾坤qiankun框架搭建 主应用为vue3的项目。
19 2
|
3天前
|
JavaScript
vue3 生命周期
【10月更文挑战第14天】vue3 生命周期
|
4天前
|
JavaScript 前端开发
Vue 2 和 Vue 3 之间响应式区别
10月更文挑战第7天
17 2
|
5天前
|
存储 前端开发 中间件
vue3之vite配置vite-plugin-mock使用mock轻松创建模拟数据提高开发效率
vue3之vite配置vite-plugin-mock使用mock轻松创建模拟数据提高开发效率
28 0
|
3天前
|
JavaScript 前端开发 API
深入探索挖掘vue3 生命周期
【10月更文挑战第10天】
13 0
|
2天前
|
缓存 JavaScript 前端开发
《基础篇第4章:vue2基础》:使用vue脚手架创建项目
《基础篇第4章:vue2基础》:使用vue脚手架创建项目
11 3
|
5天前
|
JavaScript 前端开发 开发者
Vue v-for 进阶指南:in 与 of 的区别及应用场景 | 笔记
Vue.js 中的 v-for 是强大的遍历指令,但其中的 in 和 of 关键字往往被开发者忽视。尽管它们的用法相似,但适用的场景和数据结构却各有不同。本文将详细探讨 v-for 中 in 和 of 的区别、适用场景以及在实际开发中的最佳使用时机。通过理解它们的差异,你将能够编写更加高效、简洁的 Vue.js 代码,灵活应对各种数据结构的遍历需求。
40 6
|
2天前
|
缓存 JavaScript
Vue 中 computed 与 method 的区别
【10月更文挑战第15天】computed 和 method 是 Vue 中两个重要的选项,它们在功能和特点上存在着明显的区别。理解并合理运用它们的区别,可以帮助我们构建更高效、更具可维护性的 Vue 应用。在实际开发中,要根据具体情况灵活选择使用,以满足不同的需求。
5 2
|
2天前
|
JavaScript 搜索推荐 UED
vue的自定义指令
【10月更文挑战第14天】Vue 自定义指令为我们提供了一种强大的工具,使我们能够更灵活地控制和扩展 Vue 应用的行为。通过合理地使用自定义指令,可以提高开发效率,增强应用的功能和用户体验。
|
3天前
|
JavaScript