uniapp 瀑布流双列
时间: 2025-02-14 22:18:45 浏览: 75
### 实现 UniApp 中的双列瀑布流布局
为了实现在 UniApp 中创建一个双列瀑布流布局,可以采用 CSS Grid 或者借助于一些现有的插件库。然而,当前版本的 CSS Grid 尚不支持自动流的瀑布流布局功能[^1]。
#### 使用 Vue 组件方式实现双列瀑布流布局
一种常见的方法是通过编写自定义组件并利用 JavaScript 动态计算高度差来模拟瀑布流效果:
```html
<template>
<view class="waterfall">
<!-- 左侧列表 -->
<scroll-view scroll-y class="column left-column">
<block v-for="(item, index) in itemsLeft" :key="index">
<view class="card">{{ item.content }}</view>
</block>
</scroll-view>
<!-- 右侧列表 -->
<scroll-view scroll-y class="column right-column">
<block v-for="(item, index) in itemsRight" :key="index">
<view class="card">{{ item.content }}</view>
</block>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
allItems: [
{ content: 'Item 1', height: Math.floor(Math.random() * (200 - 80)) + 80 },
// 添加更多项...
],
itemsLeft: [],
itemsRight: []
};
},
mounted() {
this.distributeItems();
},
methods: {
distributeItems() {
let currentHeightLeft = 0;
let currentHeightRight = 0;
this.allItems.forEach((item, index) => {
if (currentHeightLeft <= currentHeightRight) {
this.itemsLeft.push(item);
currentHeightLeft += item.height;
} else {
this.itemsRight.push(item);
currentHeightRight += item.height;
}
});
}
}
};
</script>
<style scoped lang="scss">
.waterfall {
display: flex;
}
.column {
width: 50%;
padding: 10px;
box-sizing: border-box;
}
.left-column,
.right-column {
.card {
margin-bottom: 10px;
background-color: #f9f9fa;
padding: 20px;
border-radius: 4px;
word-break: break-all;
}
}
</style>
```
此代码片段展示了如何在一个页面上构建两个滚动视图(`scroll-view`),分别代表左栏和右栏,并动态分配卡片到这两栏中以形成近似的瀑布流视觉效果。注意这里假设每张卡片的高度已知;实际应用时可能需要额外逻辑去测量 DOM 节点的实际尺寸。
阅读全文
相关推荐

















