Vue 手寫圖片瀑布流組件(附源碼)

前言

瀑布流,又稱瀑布流式佈局。 是比較流行的一種網站頁面佈局,視覺表現爲良莠不齊的多欄佈局,隨着頁面滾動條向下滾動,這種佈局還會不斷加載數據塊並附加至當前尾部。

最終實現效果以下css

滾動加載:

寬度自適應:
vue

原理

分析可發現,該瀑布流每一個圖片元素寬度相等,高度不一樣;且從第二行開始,每一個元素實際上都是插入到最小高度的那一列上。typescript

emmmm,就這麼簡單......數組

佈局

佈局比較簡單
容器設置'position: relative;'相對定位, 圖片元素設置'position: absolute;'絕對定位bash

<div class="waterfall_box">
  <div class="waterfall_item">
  </div>
</div>

.waterfall_box {
  position: relative;
  margin: 0 auto;
  .waterfall_item {
    float: left;
    position: absolute;
    img {
      width: 100%;
      height: auto;
    }
  }
}

實現

直接上代碼比較容易理解
Vue template 結構dom

<template>
  <div class="waterfall_box" ref="waterfall_box" :style="`height:${waterfall_box_height_exect}`">
    <template v-if="waterfall_col_num>1">
      <div v-for="(img,index) in waterfall_list" class="waterfall_item" :style="{top:img.top+'px',left:img.left+'px',width:img_width+'px',height:img.height}" :key="index">
        <slot :row="img"></slot>
      </div>
    </template>
    <!-- 列數小於1 沒有瀑布流的必要,直接正常佈局便可 -->
    <template v-else>
      <div v-for="(img,index) in img_list" :key="index" style="margin-bottom: 20px;">
        <slot :row="img"></slot>
      </div>
    </template>
  </div>
</template>

定義變量async

@Prop({ required: true, type: Array })
readonly img_list!: [];

@Prop({ required: true, type: Number }) # 圖片寬度
readonly img_width!: number;

@Prop({ required: true, type: Number }) # 圖片下邊距
readonly img_margin_bottom!: number;

img_margin_right!: number; # 圖片右邊距

/* 容器寬高 */
waterfall_box_width = 0;

waterfall_box_height = 0;

waterfall_col_num = 0; # 列數

waterfall_col_height_list: Array<number> = []; # 每列最大高度

waterfall_list = []; # 瀑布流用到的數據

接下來就是重點,也是直接上代碼函數

  1. 初始化一些必要參數
# 算出當前視圖寬度最多能夠放幾列,向下取整
  this.waterfall_col_num = Math.floor(this.waterfall_box_width / this.img_width) || 1;
  # 根據列數存儲一個臨時數組,用於存放當前每一列的最小高度
  this.waterfall_col_height_list = new Array(this.waterfall_col_num).fill(0);
  # 算出每行圖片之間的間隙
  this.img_margin_right = (this.waterfall_box_width - this.waterfall_col_num * this.img_width) / (this.waterfall_col_num - 1);
  # 只有一列,很明顯沒有瀑布流佈局的必要了,直接正常佈局
  if (this.waterfall_col_num <= 1) return;
  this.layoutWatreFall();
  1. 瀑布流佈局計算
# 用一個臨時存儲,所有計算完再更新Vue數據
  const temp_waterfall_list: any = [];
  # 遍歷每一個圖片數據,動態加一些其餘參數。每輪遍歷都把該數據加入到最小高度的那一列並設置left和top
  this.img_list.forEach((img_item: any) => {
    const minIndex = this.finMinHeightIndex();
    const img_obj = {
      ...img_item,
      url: img_item.url,
      width: this.img_width,
      height: Math.floor((this.img_width / img_item.width) * img_item.height), # 圖片等比例縮放
      top: this.waterfall_col_height_list[minIndex],
      left: minIndex * (this.img_margin_right + this.img_width),
    };
    temp_waterfall_list.push(img_obj);
    this.waterfall_col_height_list[minIndex] += img_obj.height + this.img_margin_bottom; # 每次放完元素,實時更新每一個列數的最小高度
  });
  this.waterfall_list = temp_waterfall_list;
  this.waterfall_box_height = Math.max.call(null, ...this.waterfall_col_height_list); # 更新父容器的高度
  1. 輔助函數
# 找到數組最小值下標
  finMinHeightIndex() {
    return this.waterfall_col_height_list.indexOf(Math.min.call(null, ...this.waterfall_col_height_list));
  }

源碼

使用,傳一個圖片寬度,和下邊距便可佈局

<v-water-fall :img_list="photo_list" :img_width="250" :img_margin_bottom="20" class="photo_img_box">
  <template slot-scope="scope">
    <img v-lazy="scope.row.url"> # 做用域插槽
  </template>
</v-water-fall>

源碼網站

<template>
  <div class="waterfall_box" ref="waterfall_box" :style="`height:${waterfall_box_height_exect}`">
    <template v-if="waterfall_col_num>1">
      <div v-for="(img,index) in waterfall_list" class="waterfall_item" :style="{top:img.top+'px',left:img.left+'px',width:img_width+'px',height:img.height}" :key="index">
        <slot :row="img"></slot> # 做用域插槽
      </div>
    </template>
    <!-- 列數小於1 沒有瀑布流的必要,直接正常佈局便可 -->
    <template v-else>
      <div v-for="(img,index) in img_list" :key="index" style="margin-bottom: 20px;">
        <slot :row="img"></slot> # 做用域插槽
      </div>
    </template>
  </div>
</template>

<script lang="ts">
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  Vue, Component, Prop, Watch,
} from 'vue-property-decorator';

@Component({})
export default class WaterFall extends Vue {
  @Prop({ required: true, type: Array })
  readonly img_list!: [];

  @Prop({ required: true, type: Number }) // 圖片寬度
  readonly img_width!: number;

  @Prop({ required: true, type: Number }) // 圖片下邊距
  readonly img_margin_bottom!: number;

  img_margin_right!: number; // 圖片右邊距

  /* 容器寬高 */
  waterfall_box_width = 0;

  waterfall_box_height = 0;

  waterfall_col_num = 0; // 列數

  waterfall_col_height_list: Array<number> = []; // 每列最大高度

  waterfall_list = []; // 瀑布流用到的數據

  // 容器的高度 拼上單位
  get waterfall_box_height_exect() {
    return this.waterfall_col_num <= 1 ? 'auto' : `${this.waterfall_box_height}px`;
  }

  @Watch('img_list')
  img_list_change() {
    this.initParam();
  }

  async mounted() {
    const waterfall_box_dom: any = this.$refs.waterfall_box;
    this.waterfall_box_width = waterfall_box_dom.offsetWidth;
    window.addEventListener('resize', this.afreshLayoutWaterFall);
  }

  beforeDestroy() {
    window.removeEventListener('resize', this.afreshLayoutWaterFall);
  }


  /* ---------------------- */
  initParam() {
    this.waterfall_col_num = Math.floor(this.waterfall_box_width / this.img_width) || 1;
    this.waterfall_col_height_list = new Array(this.waterfall_col_num).fill(0);
    this.img_margin_right = (this.waterfall_box_width - this.waterfall_col_num * this.img_width) / (this.waterfall_col_num - 1);
    if (this.waterfall_col_num <= 1) return;
    this.layoutWatreFall();
  }

  // 瀑布流佈局
  layoutWatreFall() {
    const temp_waterfall_list: any = [];
    this.img_list.forEach((img_item: any) => {
      const minIndex = this.finMinHeightIndex();
      const img_obj = {
        ...img_item,
        url: img_item.url,
        width: this.img_width,
        height: Math.floor((this.img_width / img_item.width) * img_item.height),
        top: this.waterfall_col_height_list[minIndex],
        left: minIndex * (this.img_margin_right + this.img_width),
      };
      temp_waterfall_list.push(img_obj);
      this.waterfall_col_height_list[minIndex] += img_obj.height + this.img_margin_bottom;
    });
    this.waterfall_list = temp_waterfall_list;
    // console.log(this.waterfall_list);
    this.waterfall_box_height = Math.max.call(null, ...this.waterfall_col_height_list);
  }

  // 找到數組最小值下標
  finMinHeightIndex() {
    return this.waterfall_col_height_list.indexOf(Math.min.call(null, ...this.waterfall_col_height_list));
  }

  afreshLayoutWaterFall() {
    const waterfall_box_dom: any = this.$refs.waterfall_box;
    if (waterfall_box_dom) {
      this.waterfall_box_width = waterfall_box_dom.offsetWidth;
      this.initParam();
    }
  }
}
</script>

<style lang="scss" scoped>
.waterfall_box {
  position: relative;
  margin: 0 auto;
  .waterfall_item {
    float: left;
    position: absolute;
    img {
      width: 100%;
      height: auto;
    }
  }
}
</style>

END

相關文章
相關標籤/搜索