7

预览图

使用教程

直接复制代码 <hd-list/> 列表布局数据自己写

<template>
  <view class="waterfall-wrap">
    <view class="waterfall-list">
      <view class="left">
        <hd-list
          :listData="item"
          v-for="(item,index) in goodsLeftList"
          :key="index"
          @onImageLoad="onImageLoad"
        ></hd-list>
      </view>
      <view class="right">
        <hd-list
          :listData="item"
          v-for="(item,index) in goodsRightList"
          :key="index"
          @onImageLoad="onImageLoad"
        ></hd-list>
      </view>
    </view>
  </view>
</template>
<script>
import hdList from "../component/hd-list.vue";
export default {
  name: "waterfall",
  props: {
    listData: {
      type: Array,
      default: []
    }
  },
  components: {
    hdList
  },
  watch: {
    /**
     * 监听listData数据
     */
    listData: {
      handler: function(data) {
        data.length > 0 && this.waterfallImage();
      },
      immediate: true
    }
  },
  data() {
    return {
      goodsListCount: 0, //加载第i张图片
      // 左侧商品列表
      goodsLeftList: [],
      goodsLeftListHeight: 0,
      // 右侧商品列表
      goodsRightList: [],
      goodsRightListHeight: 0
    };
  },
  methods: {
    // 图片绑定事件,通过比较左右列表高度,实现瀑布流展示
    onImageLoad: function(e) {
      let divWidth = 342; //显示的单栏宽度,我设为342rpx
      let oImgW = e.detail.width; //图片原始宽度
      let oImgH = e.detail.height; //图片原始高度
      let rImgH = (divWidth * oImgH) / oImgW + 32; //根据宽高比计算当前载入的图片的高度
      if (this.goodsListCount == 0) {
        this.goodsLeftListHeight += rImgH; //第一张图片高度加到goodsLeftListHeight
        this.goodsListCount++; //图片索引加1
        this.goodsRightList.push(this.listData[this.goodsListCount]); //添加第二张图片到goodsRightList数组,因为第一张已经初始化到左侧列表中
      } else {
        this.goodsListCount++; //图片索引加1
        if (this.goodsLeftListHeight > this.goodsRightListHeight) {
          //把图片的高度加到目前高度更低的栏中
          this.goodsRightListHeight += rImgH; //第二张图片高度加到goodsRightListHeight
        } else {
          this.goodsLeftListHeight += rImgH;
        }

        if (this.goodsListCount < this.listData.length) {
          //根据目前的栏高,把下一张图片,push到低的那栏
          if (this.goodsLeftListHeight > this.goodsRightListHeight) {
            this.goodsRightList.push(this.listData[this.goodsListCount]);
          } else {
            this.goodsLeftList.push(this.listData[this.goodsListCount]);
          }
        }
      }
    },
    // 向商品列表添加第一张图片
    async waterfallImage() {
      this.goodsListCount = 0;
      this.goodsLeftList.push(this.listData[0]);
    }
  }
};
</script>

兼容性

uni-app项目中使用都兼容

欢迎关注
欢迎关注小程序“进阶的大前端”,800多道前端面试题在线查看


zhou_web
1.6k 声望1.1k 粉丝