uniapp uview 房间瀑布流
时间: 2025-06-07 11:31:31 浏览: 15
### uni-app 中使用 uView 实现房间瀑布流布局的方法
在 UniApp 中利用 uView 组件库实现房间列表的瀑布流布局,主要依赖于 `u-waterfall` 组件[^1]。以下是详细的说明以及实现方法:
#### 1. **引入 uWaterfall 组件**
确保已经在项目的 `pages.json` 文件中注册了 `u-view` 的组件,并且已经安装并初始化好 uView UI 库。
```json
{
"usingComponents": {
"u-waterfall": "/wxcomponents/uview-ui/components/u-waterfall/u-waterfall",
"u-gap": "/wxcomponents/uview-ui/components/u-gap/u-gap"
}
}
```
#### 2. **页面结构设计**
在页面模板文件 `.vue` 中编写如下代码来构建基本的瀑布流框架:
```vue
<template>
<view class="content">
<u-waterfall v-if="waterfallList.length > 0" ref="uWaterfall">
<!-- 左边列内容 -->
<block slot="left-slot">
<view
class="room-item"
v-for="(item, index) in waterfallListLeft"
:key="'L' + index"
>
{{ item.name }}
</view>
</block>
<!-- 右边列内容 -->
<block slot="right-slot">
<view
class="room-item"
v-for="(item, index) in waterfallListRight"
:key="'R' + index"
>
{{ item.name }}
</view>
</block>
</u-waterfall>
<u-loadmore
status="loadstatus"
@loadmore="onLoadMore()"
></u-loadmore>
</view>
</template>
```
#### 3. **数据处理逻辑**
为了使数据能够均匀分布在两列之间,需要对原始的数据数组进行分割。可以在 Vue 的 `data()` 和 `methods` 函数里完成这些操作。
```javascript
<script>
export default {
data() {
return {
waterfallList: [], // 所有房间数据集合
waterfallListLeft: [],
waterfallListRight: [],
loadStatus: 'loading', // 加载状态
page: 1,
pageSize: 10
};
},
onLoad() {
this.fetchRoomData();
},
methods: {
fetchRoomData() {
let that = this;
// 模拟接口请求获取更多房间数据
setTimeout(() => {
const newData = Array.from({ length: that.pageSize }, (_, i) => ({
id: (that.page * that.pageSize + i).toString(),
name: `房间 ${that.page * that.pageSize + i}`
}));
if (!newData || newData.length === 0) {
that.loadStatus = 'nomore';
return;
}
that.waterfallList.push(...newData);
// 动态分配左右两侧数据
that.allocateRoomsToColumns();
that.page++;
that.loadStatus = 'loadmore'; // 更改为加载更多的状态
}, 500); // 模拟网络延迟
},
allocateRoomsToColumns() {
this.waterfallListLeft = [];
this.waterfallListRight = [];
this.waterfallList.forEach((item, idx) => {
if (idx % 2 === 0) {
this.waterfallListLeft.push(item);
} else {
this.waterfallListRight.push(item);
}
});
},
onLoadMore() {
if (this.loadStatus !== 'nomore') {
this.fetchRoomData(); // 请求新一页数据
}
}
}
};
</script>
```
#### 4. **样式定制**
为了让每个房间项看起来更美观,可以添加一些基础样式的定义:
```css
<style scoped>
.content {
padding: 10px;
}
.room-item {
background-color: #f7f8fa;
border-radius: 8px;
margin-bottom: 10px;
text-align: center;
line-height: 60px;
height: 60px;
box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
}
</style>
```
---
以上就是基于 uView 在 UniApp 上实现房间瀑布流的具体步骤和关键点[^2]。通过合理运用 `u-waterfall` 组件及其插槽机制,配合简单的业务逻辑即可轻松达成目标。
---
###
阅读全文
相关推荐

















