vue實現瀑布流布局的示例代碼
更新時間:2023年09月15日 16:35:38 作者:szx的開發(fā)筆記
這篇文章主要為大家詳細介紹了如何利用vue實現簡單的瀑布流布局,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
父組件
<template>
<WaterfallFlow :list="list"/>
</template>
<script setup lang="ts">
import WaterfallFlow from "@/components/WaterfallFlow.vue";
import {reactive} from "vue";
type listType = {
height:number,
color:string
}
// 隨機生成100個高度和顏色的對象
let list = reactive<listType[]>([
...Array.from({length:100},()=>({
height:Math.floor(Math.random()*250)+50,
color:`rgb(${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)})`
}))
])
</script>子組件
<template>
<div class="wraps">
<div v-for="item in list" class="item" :style="{
left: item.left + 'px',
top: item.top + 'px',
height: item.height + 'px',
backgroundColor: item.color,
}"></div>
</div>
</template>
<script setup lang="ts">
import {defineProps, onMounted} from "vue"
const props = defineProps<{
list: any[]
}>()
const initLayout = () => {
// 上下左右間隙距離
let margin = 10
// 每個元素的寬度
let elWidth = 120 + margin
// 每行展示的列數
let colNumber = Math.floor(document.querySelector(".app-content").clientWidth / elWidth)
// 存放元素高度的list
let heightList = []
// 遍歷所有元素
for (let i = 0; i < props.list.length; i++) {
let el = props.list[i]
// i小于colNumber表示第一行元素
if(i < colNumber){
el.top = 0
el.left = elWidth * i
heightList.push(el.height)
}else{
// 找出最小的高度
let minHeight = Math.min(...heightList)
// 找出最小高度的索引
let minHeightIndex = heightList.indexOf(minHeight)
// 設置元素的位置
el.left = elWidth * minHeightIndex
el.top = minHeight + margin
// 更新高度集合
heightList[minHeightIndex] = minHeight + el.height + margin
}
}
}
// 監(jiān)聽app-content元素的寬度變化
window.onresize = () => {
initLayout()
}
onMounted(() => {
initLayout()
})
</script>
<style scoped lang="scss">
.wraps{
height: 100%;
position: relative;
.item{
position: absolute;
width: 120px;
}
}
</style>效果展示

到此這篇關于vue實現瀑布流布局的示例代碼的文章就介紹到這了,更多相關vue瀑布流布局內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3?setup語法糖中獲取slot插槽的dom對象代碼示例
slot元素是一個插槽出口,標示了父元素提供的插槽內容將在哪里被渲染,這篇文章主要給大家介紹了關于vue3?setup語法糖中獲取slot插槽的dom對象的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04
el-table?樹形數據?tree-props?多層級使用避坑
本文主要介紹了el-table?樹形數據?tree-props?多層級使用避坑,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08

