引言:瀑布流布局的魅力與應用場景
在當今富媒體內容主導的網絡環境中,瀑布流布局已成為展示圖片商品等內容的流行方式。它通過動態布局算法在有限空間內最大化內容展示,提供視覺連續性和流暢瀏覽體驗。本文將深入探討如何使用Vue 3實現一個功能完備的瀑布流組件,并解決圖片懶加載等關鍵問題。
瀑布流組件核心實現
1. 組件設計思路
我們的瀑布流組件解決了以下關鍵問題:
- 響應式布局:根據容器寬度自動調整列數
- 高效圖片加載:支持懶加載和預加載模式
- 視覺優化:平滑的位置過渡動畫
- 錯誤處理:優雅的加載失敗處理機制
- 高定制性:通過插槽支持自定義內容
2. 核心算法實現
列數與列寬計算
const calculateColumns = () => {wrapperWidth.value = waterfallWrapper.value.clientWidth;// 響應式斷點處理const sortedBreakpoints = Object.keys(props.breakpoints).map(Number).sort((a, b) => b - a);// 根據斷點確定列數for (const breakpoint of sortedBreakpoints) {if (wrapperWidth.value >= breakpoint) {cols.value = props.breakpoints[breakpoint].rowPerView;break;}}// 計算列寬(考慮間距和對齊方式)if (props.hasAroundGutter) {colWidth.value = (wrapperWidth.value - props.gutter * 2 - (cols.value - 1) * props.gutter) / cols.value;offsetX.value = props.gutter;} else {colWidth.value = (wrapperWidth.value - (cols.value - 1) * props.gutter) / cols.value;offsetX.value = 0;}// 處理對齊方式if (props.align === 'center') {const totalWidth = cols.value * colWidth.value + (cols.value - 1) * props.gutter;offsetX.value = (wrapperWidth.value - totalWidth) / 2;} else if (props.align === 'right') {const totalWidth = cols.value * colWidth.value + (cols.value - 1) * props.gutter;offsetX.value = wrapperWidth.value - totalWidth;}
};
瀑布流布局算法
const calculateLayout = () => {const columnHeights = new Array(cols.value).fill(0);let maxHeight = 0;items.forEach((item, index) => {// 尋找高度最小的列let minColHeight = columnHeights[0];let colIndex = 0;for (let i = 1; i < cols.value; i++) {if (columnHeights[i] < minColHeight) {minColHeight = columnHeights[i];colIndex = i;}}// 計算元素位置const x = colIndex * (colWidth.value + props.gutter) + offsetX.value;const y = columnHeights[colIndex];// 應用位置變換item.style.transform = `translate3d(${x}px, ${y}px, 0)`;item.style.width = `${colWidth.value}px`;// 更新列高度const itemHeight = item.offsetHeight || 200;columnHeights[colIndex] += itemHeight + props.gutter;// 更新容器高度if (columnHeights[colIndex] > maxHeight) {maxHeight = columnHeights[colIndex];}});wrapperHeight.value = maxHeight;
};
3. 高級功能實現
智能圖片懶加載
const initLazyLoad = () => {observer.value = new IntersectionObserver((entries) => {entries.forEach(entry => {if (entry.isIntersecting) {const img = entry.target;// 設置loading占位圖if (props.loadingImg) img.src = props.loadingImg;// 延遲加載實際圖片setTimeout(() => {loadImage(img);// 圖片加載完成觸發布局更新img.onload = () => debouncedLayout();// 錯誤處理if (props.errorImg) {img.onerror = () => {img.src = props.errorImg;debouncedLayout(); // 錯誤時也更新布局};}img.removeAttribute('data-src');}, props.delay);observer.value.unobserve(img);}});}, { threshold: 0.01 });// 觀察所有懶加載圖片const lazyImages = waterfallWrapper.value.querySelectorAll('img[data-src]');lazyImages.forEach(img => observer.value.observe(img));
};
防抖優化性能
const debounce = (fn, delay) => {let timeoutId;return (...args) => {clearTimeout(timeoutId);timeoutId = setTimeout(() => fn.apply(this, args), delay);};
};// 使用防抖優化布局計算
const debouncedLayout = debounce(() => {calculateColumns();calculateLayout();
}, props.posDuration);
性能優化策略
-
GPU加速動畫
.waterfall-item {transition: transform 0.3s ease;will-change: transform; }
-
智能加載策略
- 優先加載視口內圖片
- 設置加載延遲避免卡頓
- 使用占位圖保持布局穩定
-
高效的事件處理
onMounted(() => {window.addEventListener('resize', debouncedLayout); });onUnmounted(() => {window.removeEventListener('resize', debouncedLayout);if (observer.value) observer.value.disconnect(); });
-
響應式斷點設計
breakpoints: {1200: { rowPerView: 4 },800: { rowPerView: 3 },500: { rowPerView: 2 } }
常見問題解決方案
-
圖片加載導致布局抖動問題
- 使用固定比例的占位圖容器
- 預先設置圖片尺寸屬性
- 添加加載過渡動畫
-
白屏問題處理
// 確保初始渲染可見 nextTick(() => {calculateColumns();calculateLayout(); });
-
大量數據性能優化
- 虛擬滾動技術
- 分頁加載
- 回收不可見DOM節點
總結
通過本文,我們實現了一個高性能可定制的Vue 3瀑布流組件,它具有以下特點:
- 智能化布局:自動計算最佳列數和位置
- 多種加載模式:支持懶加載和預加載
- 響應式設計:完美適配不同屏幕尺寸
- 優雅的錯誤處理:提供自定義占位圖
- 平滑動畫:GPU加速的位置過渡效果
插件完整代碼:
<template><div ref="waterfallWrapper" class="waterfall-list" :style="{ height: `${wrapperHeight}px` }"><div v-for="(item, index) in list" :key="getKey(item, index)" class="waterfall-item"><slot name="item" :item="item" :index="index" :url="getRenderURL(item)" /></div></div>
</template><script>
import { ref, watch, onMounted, onUnmounted, provide, nextTick } from "vue";export default {name: 'WaterfallList',props: {list: {type: Array,required: true,default: () => []},rowKey: {type: String,default: "id"},imgSelector: {type: String,default: "src"},width: {type: Number,default: 200},breakpoints: {type: Object,default: () => ({1200: { rowPerView: 4 },800: { rowPerView: 3 },500: { rowPerView: 2 }})},gutter: {type: Number,default: 10},hasAroundGutter: {type: Boolean,default: true},posDuration: {type: Number,default: 300},align: {type: String,default: "center",validator: (value) => ['left', 'center', 'right'].includes(value)},lazyLoad: {type: Boolean,default: true},crossOrigin: {type: Boolean,default: true},delay: {type: Number,default: 300},loadingImg: {type: String,default: ''},errorImg: {type: String,default: ''}},setup(props, { emit }) {const waterfallWrapper = ref(null);const wrapperWidth = ref(0);const colWidth = ref(0);const cols = ref(0);const offsetX = ref(0);const wrapperHeight = ref(0);const observer = ref(null);// 計算列數和列寬const calculateColumns = () => {if (!waterfallWrapper.value) return;wrapperWidth.value = waterfallWrapper.value.clientWidth;// 根據斷點確定列數const sortedBreakpoints = Object.keys(props.breakpoints).map(Number).sort((a, b) => b - a); // 從大到小排序let foundCols = 1;for (const breakpoint of sortedBreakpoints) {if (wrapperWidth.value >= breakpoint) {foundCols = props.breakpoints[breakpoint].rowPerView;break;}}cols.value = foundCols;// 計算列寬if (props.hasAroundGutter) {colWidth.value = (wrapperWidth.value - props.gutter * 2 - (cols.value - 1) * props.gutter) / cols.value;offsetX.value = props.gutter;} else {colWidth.value = (wrapperWidth.value - (cols.value - 1) * props.gutter) / cols.value;offsetX.value = 0;}// 處理對齊方式if (props.align === 'center') {const totalWidth = cols.value * colWidth.value + (cols.value - 1) * props.gutter;offsetX.value = (wrapperWidth.value - totalWidth) / 2;} else if (props.align === 'right') {const totalWidth = cols.value * colWidth.value + (cols.value - 1) * props.gutter;offsetX.value = wrapperWidth.value - totalWidth;}};// 加載圖片const loadImage = (img) => {const url = img.dataset?.src || img.getAttribute('data-src');if (url) {// 創建臨時Image對象預加載const tempImage = new Image();tempImage.onload = () => {img.src = url;if (props.crossOrigin) img.crossOrigin = 'anonymous';img.removeAttribute('data-src');debouncedLayout(); // 關鍵:加載完成后觸發布局更新};tempImage.onerror = () => {if (props.errorImg) img.src = props.errorImg;img.removeAttribute('data-src');debouncedLayout(); // 關鍵:加載失敗時也觸發布局更新};tempImage.src = url;return true;}return false;};// 加載所有圖片(修改后)const loadAllImages = () => {if (!waterfallWrapper.value) return;const images = waterfallWrapper.value.querySelectorAll('img[data-src]');images.forEach(img => {// 設置loading占位圖if (props.loadingImg) img.src = props.loadingImg;// 加載實際圖片并監聽加載完成事件const loaded = loadImage(img);// 錯誤處理if (loaded && props.errorImg) {img.onerror = () => {img.src = props.errorImg;debouncedLayout(); // 關鍵:錯誤時也觸發布局更新};}});};// const loadAllImages = () => {// if (!waterfallWrapper.value) return;// const images = waterfallWrapper.value.querySelectorAll('img');// images.forEach(img => {// // 如果已經是加載狀態則跳過// if (img.src && !img.src.includes(props.loadingImg)) return;// // 嘗試加載圖片// const loaded = loadImage(img);// // 設置錯誤處理// if (loaded && props.errorImg) {// img.onerror = () => {// img.src = props.errorImg;// };// }// });// };// 初始化懶加載const initLazyLoad = () => {if (!waterfallWrapper.value) return;// 清理舊的觀察器if (observer.value) {observer.value.disconnect();}// 創建新的觀察器observer.value = new IntersectionObserver((entries) => {entries.forEach(entry => {if (entry.isIntersecting) {const img = entry.target;if (img.dataset?.src || img.getAttribute('data-src')) {// 設置loading占位圖if (props.loadingImg) {img.src = props.loadingImg;}// 延遲加載實際圖片setTimeout(() => {loadImage(img);img.onload = () => debouncedLayout();if (props.errorImg) {img.onerror = () => {img.src = props.errorImg;};}// 移除data-src屬性img.removeAttribute('data-src');}, props.delay);}observer.value.unobserve(img);}});}, { threshold: 0.01 });// 觀察所有懶加載圖片const lazyImages = waterfallWrapper.value.querySelectorAll('img[data-src]');lazyImages.forEach(img => {observer.value.observe(img);});};// 計算布局const calculateLayout = () => {if (!waterfallWrapper.value || cols.value === 0) return;const items = waterfallWrapper.value.querySelectorAll('.waterfall-item');if (items.length === 0) return;const columnHeights = new Array(cols.value).fill(0);let maxHeight = 0;items.forEach((item, index) => {let minColHeight = columnHeights[0];let colIndex = 0;for (let i = 1; i < cols.value; i++) {if (columnHeights[i] < minColHeight) {minColHeight = columnHeights[i];colIndex = i;}}const x = colIndex * (colWidth.value + props.gutter) + offsetX.value;const y = columnHeights[colIndex];item.style.transform = `translate3d(${x}px, ${y}px, 0)`;item.style.width = `${colWidth.value}px`;item.style.position = 'absolute';item.style.left = '0';item.style.top = '0';item.style.visibility = 'visible';// 計算項目高度(包含所有圖片)const itemHeight = item.offsetHeight || 200;columnHeights[colIndex] += itemHeight + props.gutter;// 更新最大高度if (columnHeights[colIndex] > maxHeight) {maxHeight = columnHeights[colIndex];}});wrapperHeight.value = maxHeight;emit('afterRender');};// 防抖函數const debounce = (fn, delay) => {let timeoutId;return (...args) => {clearTimeout(timeoutId);timeoutId = setTimeout(() => fn.apply(this, args), delay);};};const debouncedLayout = debounce(() => {calculateColumns();calculateLayout();}, props.posDuration);// 初始化onMounted(() => {if (!waterfallWrapper.value) return;calculateColumns();nextTick(() => {if (props.lazyLoad) {initLazyLoad();} else {loadAllImages(); // 非懶加載模式直接加載圖片}calculateLayout(); // 初始布局});window.addEventListener('resize', debouncedLayout);});// 清理onUnmounted(() => {if (observer.value) {observer.value.disconnect();}window.removeEventListener('resize', debouncedLayout);});// 監聽數據變化(修改部分)watch(() => props.list, () => {debouncedLayout();nextTick(() => {if (props.lazyLoad) {initLazyLoad();} else {// 延遲加載確保DOM更新完成setTimeout(loadAllImages, 0);}});}, { deep: true });// 提供刷新方法provide('refreshWaterfall', debouncedLayout);const getRenderURL = (item) => {return item[props.imgSelector];};const getKey = (item, index) => {return item[props.rowKey] || index;};return {waterfallWrapper,wrapperHeight,getRenderURL,getKey};}
};
</script><style scoped>
.waterfall-list {position: relative;width: 100%;margin: 0 auto;
}.waterfall-item {position: absolute;visibility: hidden;transition: transform 0.3s ease;will-change: transform;box-sizing: border-box;
}
</style>
調用示例:
<template><div class="container"><h1>圖片瀑布流懶加載示例</h1><!-- 瀑布流組件 --><waterfall-list :list="imageList" :lazy-load="false" :cross-origin="true" :delay="300"loading-img="https://via.placeholder.com/300x200?text=Loading..."error-img="https://via.placeholder.com/300x200?text=Error" :width="300" :gutter="15" @afterRender="onAfterRender"><template #item="{ item, url }"><div class="image-card"><!-- 使用data-src實現懶加載 --><img :data-src="url" :alt="item.title" class="image" @load="onImageLoad" /><div class="info"><h3>{{ item.title }}</h3><p>{{ item.description }}</p></div></div></template></waterfall-list><!-- 加載更多按鈕 --><button class="load-more" @click="loadMoreImages" :disabled="isLoading">{{ isLoading ? '加載中...' : '加載更多' }}</button></div>
</template><script>
import { ref } from 'vue';
import WaterfallList from '../components/vWaterfall.vue'; // 根據實際路徑調整export default {components: {WaterfallList},setup() {// 模擬圖片數據const generateImages = (count, startIndex = 0) => {return Array.from({ length: count }, (_, i) => ({id: startIndex + i,title: `圖片 ${startIndex + i + 1}`,description: `這是第 ${startIndex + i + 1} 張圖片的描述`,src: `https://picsum.photos/id/${startIndex + i + 10}/300/200`}));};const imageList = ref(generateImages(12));const isLoading = ref(false);// 圖片加載完成回調const onImageLoad = (e) => {console.log('圖片加載完成', e.target);};// 瀑布流渲染完成回調const onAfterRender = () => {console.log('瀑布流布局完成');};// 加載更多圖片const loadMoreImages = () => {isLoading.value = true;setTimeout(() => {const newImages = generateImages(6, imageList.value.length);imageList.value = [...imageList.value, ...newImages];isLoading.value = false;}, 1000);};return {imageList,isLoading,onImageLoad,onAfterRender,loadMoreImages};}
};
</script><style scoped>
.container {max-width: 1200px;margin: 0 auto;padding: 20px;
}h1 {text-align: center;margin-bottom: 30px;color: #333;
}.image-card {background: #fff;border-radius: 8px;overflow: hidden;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);transition: transform 0.3s ease;
}.image-card:hover {transform: translateY(-5px);
}.image {width: 100%;height: auto;display: block;background: #f5f5f5;transition: opacity 0.3s ease;
}.info {padding: 15px;
}.info h3 {margin: 0 0 8px 0;font-size: 16px;color: #333;
}.info p {margin: 0;font-size: 14px;color: #666;
}.load-more {display: block;width: 200px;margin: 30px auto;padding: 12px 24px;background: #4a8cff;color: white;border: none;border-radius: 4px;font-size: 16px;cursor: pointer;transition: background 0.3s ease;
}.load-more:hover {background: #3a7be0;
}.load-more:disabled {background: #ccc;cursor: not-allowed;
}
</style>