分享个瀑布流的写法,用了插件市场的感觉都没有太简易灵活的。
测试了下 网页/小程序/安卓的显示效果,还可以好像。
<template>
<div class="index-waterfall">
<view v-for="(column, columnIndex) of columnData" :key="columnIndex" class="column flex">
<view v-for="item of column" :key="item.id" class="ceil" :style="{ height: item.height }">{{ item.id }}</view>
</view>
</div>
</template>
<script>
export default {
data() {
const columnNum = 2
return {
fallData: [],
columnData: Array(columnNum).fill('').map(() => [])
};
},
created() {
const height = ['100rpx', '150rpx', '200rpx', '125rpx', '175rpx'];
this.fallData = Array(50).fill('').map((item, index) => {
return {
height: height[Math.floor(Math.random() * height.length)],
id: index
};
});
},
mounted() {
this.pushItem()
},
methods: {
pushItem() {
const query = uni.createSelectorQuery().in(this)
query.selectAll('.column').fields({ size: true }).exec(result => {
const columns = result[0]
let minTop = columns[0].height
let minColumnIndex = 0
columns.forEach((item, index) => {
if (item.height < minTop) {
minTop = item.height
minColumnIndex = index
}
})
this.columnData[minColumnIndex].push(this.fallData.shift())
this.fallData.length && this.$nextTick(() => this.pushItem())
})
}
}
};
</script>
<style lang="scss" scoped>
.index-waterfall {
width: 100%;
display: flex;
justify-content: space-between;
align-items: flex-start;
.column {
flex: 0 0 calc(50% - 10rpx);
flex-direction: column;
}
.ceil {
width: 100%;
float: left;
margin-top: 30rpx;
background-color: #fff;
}
}
</style>