效果:
代码:
APP.vue
<template>
<waterFallVue :list="list"></waterFallVue>
</template>
<script setup>
import waterFallVue from "./components/waterFallVue .vue"
const list = [
{
height: 300,
background: 'red'
},
{
height: 400,
background: 'pink'
},
{
height: 500,
background: 'blue'
},
{
height: 200,
background: 'green'
},
{
height: 300,
background: 'gray'
},
{
height: 400,
background: '#CC00FF'
},
{
height: 200,
background: 'black'
},
{
height: 100,
background: '#996666'
},
{
height: 500,
background: 'skyblue'
},
{
height: 300,
background: '#993366'
},
{
height: 100,
background: '#33FF33'
},
{
height: 400,
background: 'skyblue'
},
{
height: 200,
background: '#6633CC'
},
{
height: 300,
background: '#666699'
},
{
height: 300,
background: '#66CCFF'
},
{
height: 300,
background: 'skyblue'
},
{
height: 200,
background: '#CC3366'
},
{
height: 200,
background: '#CC9966'
},
{
height: 200,
background: '#FF00FF'
},
{
height: 500,
background: '#990000'
},
{
height: 400,
background: 'red'
},
{
height: 100,
background: '#999966'
},
{
height: 200,
background: '#CCCC66'
},
{
height: 300,
background: '#FF33FF'
},
{
height: 400,
background: '#FFFF66'
},
{
height: 200,
background: 'red'
},
{
height: 100,
background: 'skyblue'
},
{
height: 200,
background: '#33CC00'
},
{
height: 300,
background: '#330033'
},
{
height: 100,
background: '#0066CC'
},
{
height: 200,
background: 'skyblue'
},
{
height: 100,
background: '#006666'
},
{
height: 200,
background: 'yellow'
},
{
height: 300,
background: 'yellow'
},
{
height: 100,
background: '#33CCFF'
},
{
height: 400,
background: 'yellow'
},
{
height: 400,
background: 'yellow'
},
{
height: 200,
background: '#33FF00'
},
{
height: 300,
background: 'yellow'
},
{
height: 100,
background: 'green'
}
]
waterFallVue.vue
<template>
<div class='wrap'>
<div :style="{height:item.height + 'px', background: item.background, left: item.left + 'px', top: item.top +'px'}" v-for="(item,index) in wareList" :key="index" class="items">
<div>{{index}}</div>
<div>{{item.height}}</div>
</div>
</div>
</template>
<script setup>
// 瀑布流布局
import { onMounted , reactive} from 'vue';
const {list} = defineProps({
list: {
type: Array
}
})
let wareList = reactive([]);
let heightList = reactive([]);
onMounted(()=> {
let x = document.body.clientWidth
let width = 130;
let column = Math.floor(x / width)
console.log(column);
for(let i = 0; i<list.length; i++) {
if( i < column) {
list[i].left = width * i;
list[i].top = 0;
wareList.push(list[i])
heightList.push(list[i].height)
}else {
let bigHeight = heightList[0];
let flag = 0;
heightList.forEach((item,index) => {
if(bigHeight > item) {
bigHeight = item
flag = index
}
})
list[i].left = flag * width;
list[i].top = bigHeight + 20;
heightList[flag] = list[i].height + heightList[flag];
wareList.push(list[i])
}
}
})
</script>
<style lang='scss'>
.wrap {
position: relative;
height: 100%;
overflow: auto;
.items {
position: absolute;
width: 120px;
}
}
</style>