Vue3+Ts 瀑布式布局

400 阅读1分钟

组件接收传过来的图片url(数组)

<template>
  <div class="itemsbox">
    <img
      v-for="(item, index) in emit.yui"
      :key="index"
      :src="item"
      class="items"
      :style="{ width: 200 + 'px', left: lefts[index] + 'px' ,top: imgtop[index] + 'px' }"
      @load="init(index)"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, onMounted } from "vue";
const emit = defineProps<{
  yui: any[];
}>();
let lefts = ref<any>([]);
let imgheight: number[] = [];
let imgtop = ref<any>([]);
const top: any = 20;
const init = async (index: number) => {
  console.log(index);
  const winwidth = document.body.clientWidth;
  const num = Math.floor(winwidth / 220);
  // console.log(num);
  // for (let index = 0; index < emit.yui.length; index++) {
  if (index < num) {
    if (index < num) {
      lefts.value[index] = index * (200 + 20);
      let bili  = (document.querySelector(`.itemsbox :nth-child(${index+1})`) as HTMLImageElement ).naturalWidth/200;
      imgheight[index]  = (document.querySelector(`.itemsbox :nth-child(${index+1})`) as HTMLImageElement ).naturalHeight/ bili   + top;
      imgtop.value[index] = 0;
    }
  } else {
    let minheight: any = imgheight[0];
    let minindex: number = 0;
    // console.log(imgheight.value);
    for (let i = 0; i < num; i++) {
      if (imgheight[i] < minheight) {
        minheight = imgheight[i];
        minindex = i;
      }
    }
    lefts.value[index] = minindex * (200 + 20);
    let bili  = (document.querySelector(`.itemsbox :nth-child(${index+1})`) as HTMLImageElement ).naturalWidth/200;
    imgtop.value[index] = imgheight[minindex];
    imgheight[minindex] = (document.querySelector(`.itemsbox :nth-child(${index+1})`) as HTMLImageElement ).naturalHeight/ bili + minheight  + top;
  }
  // }
};
</script>
<style>
.items{
  position: absolute;
}
</style>

捕获.PNG