一、介绍

瀑布流,又称为瀑布流布局。是比较流行的一种网页展示形式,在视觉上表现为参差不齐的多栏布局,随着页面滚动条向下滚动,这种布局还会不断加载数据块并附加至当前尾部。即多行等宽元素排列,后面的元素依次添加到其后,等宽不等高,根据图片原比例缩放直至宽度达到我们的要求,依次按照规则放入指定位置。

二、布局原理

等宽不等高的图片排列,从第二行开始,图片插入的位置根据上一行插入图片得最低处依次插入,最终形成参差不齐的布局效果。

三、具体实现

这里是根据移动端项目实现(两栏效果)

<template>
  <div class="waterfall-container" >
    <div v-for="(item, index) in list" :key="index" class="list">
      <div
        v-for="(it, key) in item"
        :key="key"
        class="item"
        :style="{ height: `${it.itemHeight}rem` }"
      >
        <img
          class="cover"
          :key="it.thumb_path"
          src="https://img1.halobear.com/upload_page/FvZmzzPmEhvRzE7ThqyrjcSZXAg_.png"
          v-lazy="it.thumb_path"
          :style="{ height: `${it.imageHeight}rem` }"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      index: 0
    };
  },
  computed: {
    list() {
      let leftHeight = 0;
      // let middleHeight = 0;
      let rightHeight = 0;
      const leftData = [];
      // const middleData = [];
      const rightData = [];
      this.data.forEach(item => {
        const w = item.width || item.cover_width;
        const h = item.height || item.cover_height;
        if (!item.imageHeight) {
          item.imageHeight = (((h || 100) / (w || 100)) * 324) / 100;
        }
        // if (Math.min(leftHeight, middleHeight, rightHeight) == leftHeight) {
        //   leftHeight += item.imageHeight;
        //   leftData.push(item);
        // } else if (
        //   Math.min(leftHeight, middleHeight, rightHeight) == middleHeight
        // ) {
        //   middleHeight += item.imageHeight;
        //   middleData.push(item);
        // } else {
        //   rightHeight += item.imageHeight;
        //   rightData.push(item);
        // }
        
        if (leftHeight <= rightHeight) {
          leftHeight += item.imageHeight;
          leftData.push(item);
        } else {
          rightHeight += item.imageHeight;
          rightData.push(item);
        }
      });
      return [leftData, rightData];
      // return [leftData, middleData, rightData];
    }
  },
};
</script>

<style lang="less" scoped>
.waterfall-container {
  display: flex;
  justify-content: space-between;
  padding: 0 30px 40px;
  .list {
    width: 339px;
  }
  .item {
    display: block;
    width: 100%;
    margin-bottom: 0.12rem;
  }
  .cover {
    width: 100%;
    background: block;
    border-radius: 6px;
    background: #f0f2f5;
    opacity: 0.5;
  }
  .fadeIn {
    transition: all 1s;
    opacity: 1;
  }
}
</style>

四、实现效果

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐