vue简单实现瀑布流
Vue 实现瀑布流布局
使用 Vue 实现瀑布流布局可以通过 CSS 或 JavaScript 计算元素位置。以下是两种常见方法:
方法一:纯 CSS 多列布局
利用 CSS 的 column-count 和 column-gap 属性快速实现基础瀑布流。
<template>
<div class="waterfall-container">
<div v-for="(item, index) in items" :key="index" class="waterfall-item">
<img :src="item.image" :alt="item.title">
<p>{{ item.title }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ image: 'image1.jpg', title: 'Item 1' },
// 更多数据...
]
}
}
}
</script>
<style>
.waterfall-container {
column-count: 3;
column-gap: 15px;
}
.waterfall-item {
break-inside: avoid;
margin-bottom: 15px;
}
</style>
方法二:JavaScript 动态计算位置
通过计算每个元素的位置实现更灵活的瀑布流。
<template>
<div class="waterfall" ref="waterfall">
<div
v-for="(item, index) in items"
:key="index"
class="item"
:style="{ top: `${item.top}px`, left: `${item.left}px`, height: `${item.height}px` }"
>
<img :src="item.image">
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
columnWidth: 200,
gap: 15,
columns: 0,
columnHeights: []
}
},
mounted() {
this.initData();
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
initData() {
// 模拟数据
this.items = Array(10).fill().map((_, i) => ({
image: `image${i+1}.jpg`,
height: 100 + Math.random() * 200
}));
this.calculateLayout();
},
calculateLayout() {
const containerWidth = this.$refs.waterfall.offsetWidth;
this.columns = Math.floor(containerWidth / (this.columnWidth + this.gap));
this.columnHeights = Array(this.columns).fill(0);
this.items.forEach(item => {
const minHeight = Math.min(...this.columnHeights);
const columnIndex = this.columnHeights.indexOf(minHeight);
item.left = columnIndex * (this.columnWidth + this.gap);
item.top = minHeight;
this.columnHeights[columnIndex] += item.height + this.gap;
});
},
handleResize() {
this.calculateLayout();
}
}
}
</script>
<style>
.waterfall {
position: relative;
margin: 0 auto;
}
.item {
position: absolute;
width: 200px;
overflow: hidden;
}
</style>
方法三:使用现成库
可以借助现有 Vue 瀑布流组件快速实现:
-
安装 vue-waterfall 插件:
npm install vue-waterfall --save -
在组件中使用:
<template> <waterfall :col="3" :data="items"> <template> <div class="cell-item" v-for="(item, index) in items" :key="index"> <img :src="item.image" alt="加载错误"> <div class="item-body"> <div class="item-desc">{{item.title}}</div> </div> </div> </template> </waterfall> </template>
export default { components: { Waterfall }, data() { return { items: [] // 你的数据 } } }
```以上三种方法可根据项目需求选择,CSS 方法最简单但灵活性有限,JavaScript 方法最灵活但需要更多代码,使用现成库则能快速实现专业效果。







