父组件
<script setup lang="ts">
import { reactive } from "@vue/reactivity";
import HelloWorld from "./components/HelloWorld.vue";
import waterFall from "./components/water-fall.vue";
const list = reactive([
{
height: 300,
background: "red",
},
{
height: 400,
background: "pink",
},
{
height: 500,
background: "blue",
},
{
height: 200,
background: "green",
},
{
height: 300,
background: "skyBlue",
},
{
height: 100,
background: "yellow",
},
{
height: 300,
background: "gray",
},
{
height: 500,
background: "blue",
},
{
height: 200,
background: "green",
},
{
height: 300,
background: "skyBlue",
},
]);
</script>
<template>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</a>
<a href="https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>
</div>
<HelloWorld msg="Vite + Vue" />
<waterFall :list="list" />
</template>
<style scoped>
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
子组件
<template>
<div class="wraps">
<div
v-for="item in waterList"
class="items"
:style="{
height: item.height + 'px',
background: item.background,
left: item.left + 'px',
top: item.top + 'px',
}"
></div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, reactive } from "vue";
const props = defineProps<{ list: any[] }>();
const waterList = reactive<any[]>([]);
const heightList: number[] = [];
const init = () => {
const width = 130;
const x = document.body.clientWidth;
const column = Math.floor(x / width); //向下取整
console.log(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]);
console.log(current);
}
}
};
onMounted(() => {
init();
});
</script>
<style scoped lang="less">
.wraps {
position: relative;
.items {
position: absolute;
width: 120px;
}
}
</style>