vue实现瀑布流
Vue 实现瀑布流的方法
使用 CSS 多列布局
CSS 的 column-count 和 column-gap 属性可以快速实现简单的瀑布流效果。这种方法适合静态内容,但动态加载时可能存在问题。
<template>
<div class="waterfall">
<div v-for="item in items" :key="item.id" class="item">
<img :src="item.img" alt="">
</div>
</div>
</template>
<style>
.waterfall {
column-count: 3;
column-gap: 15px;
}
.item {
break-inside: avoid;
margin-bottom: 15px;
}
</style>
使用 Flexbox 布局
Flexbox 布局需要手动计算高度,适合动态加载的场景。
<template>
<div class="waterfall">
<div v-for="(column, index) in columns" :key="index" class="column">
<div v-for="item in column" :key="item.id" class="item">
<img :src="item.img" alt="">
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 数据源
columns: [[], [], []] // 三列
}
},
mounted() {
this.distributeItems();
},
methods: {
distributeItems() {
this.items.forEach(item => {
const shortestColumn = this.getShortestColumn();
shortestColumn.push(item);
});
},
getShortestColumn() {
return this.columns.reduce((prev, curr) =>
curr.length < prev.length ? curr : prev
);
}
}
}
</script>
<style>
.waterfall {
display: flex;
justify-content: space-between;
}
.column {
flex: 1;
margin: 0 10px;
}
.item {
margin-bottom: 20px;
}
</style>
使用第三方库
Vue 社区提供了专门的瀑布流组件,如 vue-waterfall 和 vue-masonry,可以简化实现过程。

安装 vue-waterfall:
npm install vue-waterfall --save
使用示例:

<template>
<waterfall :col="3" :data="items">
<template>
<div class="item" v-for="item in items" :key="item.id">
<img :src="item.img" alt="">
</div>
</template>
</waterfall>
</template>
<script>
import Waterfall from 'vue-waterfall';
export default {
components: { Waterfall },
data() {
return {
items: [] // 数据源
}
}
}
</script>
响应式处理
为了适应不同屏幕尺寸,可以监听窗口大小变化动态调整列数。
export default {
data() {
return {
columnCount: 3
}
},
mounted() {
window.addEventListener('resize', this.handleResize);
this.handleResize();
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
const width = window.innerWidth;
this.columnCount = width < 600 ? 1 : width < 900 ? 2 : 3;
}
}
}
图片懒加载
结合 IntersectionObserver 或 vue-lazyload 实现图片懒加载,优化性能。
import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: 'loading.gif',
attempt: 1
});
<img v-lazy="item.img" alt="">
以上方法可以根据项目需求选择,CSS 多列布局适合简单场景,Flexbox 适合动态内容,第三方库能快速实现复杂需求。






