詳解Vue3如何優(yōu)雅的加載大量圖片
更新時間:2023年09月18日 08:25:52 作者:萌萌噠草頭將軍
最近開發(fā)了一個功能,頁面首頁會加載大量的圖片,初次進入頁面時,會導致頁面性能下降,于是乎,我改進了這個功能,可以讓所有圖片自動懶加載,文中有詳細的代碼示例,需要的朋友可以參考下
原理
這個功能主要的底層邏輯是是使用IntersectionObserver API,IntersectionObserver用于在瀏覽器中觀察元素的可見性和位置變化。它可以幫助開發(fā)者實現一些動態(tài)行為,如圖片的懶加載、無限滾動等。
簡單的示例如下:
// 創(chuàng)建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,基本的功能如下:
- 給圖片提供默認的占位圖片
src,同時提供data-src屬性 - 傳入圖片對應的
ref屬性。 - 當圖片進入可視區(qū)域時,使用
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>實際效果如下

雖然基本的功能要求已經完成了,但是現在還不夠優(yōu)雅?。?!
優(yōu)化
接下來,我們增加個過渡動畫。每次當加載完圖片,就從占位圖過渡到正常圖片模式。
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>以上就是詳解Vue3如何優(yōu)雅的加載大量圖片的詳細內容,更多關于Vue3加載大量圖片的資料請關注腳本之家其它相關文章!
相關文章
Vue動態(tài)生成el-checkbox點擊無法賦值的解決方法
這篇文章主要給大家介紹了關于Vue動態(tài)生成el-checkbox點擊無法賦值的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-02-02

