瀑布流

发布时间 2023-11-09 15:32:42作者: 芬-mi

辅助见向子组件传递每个块的值

<template>
    <water_fall :list="div_list"></water_fall>
</template>
<script>
    
import water_fall from './components/water_fall.vue'

  const div_list=[
    {
      height:300,
      background:'red'
    },
    {
      height:400,
      background:'pink'
    },
    {
      height:200,
      background:'green'
    },
    ......
  ]

</script>

子组件接收块元素,并设置每个块的位置

<template>
    <div class="wraps">
        <div :style="{ height:item.height+'px',background:item.background,left:item.left+'px',top:item.top+'px' }" class="items" v-for="item in waterList"></div>
    </div>
</template>
<script setup lang="ts">
    import { onMounted,reactive } from 'vue';
    const props=defineProps<{
        list:any[]
    }>()
    
    const waterList=reactive<any[]>([]);
    const heightList=reactive<any[]>([])
    const init=()=>{
        const width=130;
        const x=document.body.clientWidth
        const column=Math.floor(x/width)
        for(let i=0;i<props.list.length;i++){
            if(i<column){
                props.list[i].left=i*width;
                props.list[i].top=20;
                waterList.push(props.list[i])
                heightList.push(props.list[i].height)
            }else{
                let current=heightList[0]
                let index=0;
                heightList.forEach((h,i)=>{
                    if(current>h){
                        current=h;
                        index=i;
                    }
                })
                props.list[i].top=current+20
                props.list[i].left=index*width;
                heightList[index]=heightList[index]+props.list[i].height+20;
                waterList.push(props.list[i])
            }
        }
    }

    onMounted(()=>{
        init()
    })
</script>
<style scoped lang="less">
    .wraps{
        position: relative;
        .items{
            position: absolute;
            width: 120px;
        }
    }
</style>