vue瀑布流实现
Vue 瀑布流实现方法
使用 CSS Grid 实现
CSS Grid 提供了一种简单的方式来实现瀑布流布局。通过设置 grid-auto-flow: dense 和 grid-template-columns 可以创建自适应列数的瀑布流。
<template>
<div class="waterfall-grid">
<div v-for="(item, index) in items" :key="index" class="waterfall-item">
<!-- 内容 -->
</div>
</div>
</template>
<style>
.waterfall-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-flow: dense;
gap: 16px;
}
.waterfall-item {
break-inside: avoid;
}
</style>
使用 CSS Columns 实现
CSS 多列布局是另一种原生支持的瀑布流实现方式,适合内容高度不固定的场景。
<template>
<div class="waterfall-columns">
<div v-for="(item, index) in items" :key="index" class="waterfall-item">
<!-- 内容 -->
</div>
</div>
</template>
<style>
.waterfall-columns {
column-count: 3;
column-gap: 16px;
}
.waterfall-item {
display: inline-block;
width: 100%;
margin-bottom: 16px;
}
</style>
使用第三方库 vue-waterfall
对于更复杂的需求,可以使用专门为 Vue 设计的瀑布流库如 vue-waterfall。
安装:
npm install vue-waterfall --save
使用示例:
<template>
<waterfall
:col="3"
:data="items"
@loadmore="loadMore"
>
<template #item="{item}">
<!-- 自定义内容 -->
</template>
</waterfall>
</template>
<script>
import Waterfall from 'vue-waterfall'
export default {
components: { Waterfall },
data() {
return {
items: [...] // 数据源
}
},
methods: {
loadMore() {
// 加载更多数据
}
}
}
</script>
响应式调整
为适应不同屏幕尺寸,可以添加响应式逻辑:
export default {
data() {
return {
columnCount: 3
}
},
mounted() {
this.updateColumns()
window.addEventListener('resize', this.updateColumns)
},
beforeDestroy() {
window.removeEventListener('resize', this.updateColumns)
},
methods: {
updateColumns() {
const width = window.innerWidth
this.columnCount = width < 600 ? 1 : width < 900 ? 2 : 3
}
}
}
图片懒加载优化
结合 IntersectionObserver 实现图片懒加载,提升性能:
<template>
<div class="waterfall">
<div v-for="(item, index) in items" :key="index" ref="items">
<img v-if="item.visible" :src="item.src">
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 包含visible属性
observer: null
}
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const index = [...this.$refs.items].indexOf(entry.target)
this.$set(this.items[index], 'visible', true)
this.observer.unobserve(entry.target)
}
})
})
this.$nextTick(() => {
this.$refs.items.forEach(el => this.observer.observe(el))
})
}
}
</script>
性能优化建议
- 使用虚拟滚动技术处理大量数据
- 对图片进行尺寸优化和压缩
- 实现数据分页加载
- 避免频繁的DOM操作
- 使用CSS will-change属性提升动画性能







