vue實(shí)現(xiàn)瀑布流布局的示例代碼
父組件
<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
}
// 隨機(jī)生成100個(gè)高度和顏色的對(duì)象
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
// 每個(gè)元素的寬度
let elWidth = 120 + margin
// 每行展示的列數(shù)
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)
// 設(shè)置元素的位置
el.left = elWidth * minHeightIndex
el.top = minHeight + margin
// 更新高度集合
heightList[minHeightIndex] = minHeight + el.height + margin
}
}
}
// 監(jiān)聽(tīng)app-content元素的寬度變化
window.onresize = () => {
initLayout()
}
onMounted(() => {
initLayout()
})
</script>
<style scoped lang="scss">
.wraps{
height: 100%;
position: relative;
.item{
position: absolute;
width: 120px;
}
}
</style>效果展示

到此這篇關(guān)于vue實(shí)現(xiàn)瀑布流布局的示例代碼的文章就介紹到這了,更多相關(guān)vue瀑布流布局內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue使用require.context實(shí)現(xiàn)動(dòng)態(tài)注冊(cè)路由
這篇文章主要介紹了vue使用require.context實(shí)現(xiàn)動(dòng)態(tài)注冊(cè)路由的方法,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12
vue實(shí)現(xiàn)評(píng)價(jià)星星功能
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)評(píng)價(jià)星星功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
Vue之修改數(shù)據(jù)頁(yè)面不更新的問(wèn)題
這篇文章主要介紹了Vue之修改數(shù)據(jù)頁(yè)面不更新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
解決vue數(shù)據(jù)更新但table內(nèi)容不更新的問(wèn)題
這篇文章主要給大家介紹了vue數(shù)據(jù)更新table內(nèi)容不更新解決方法,文中有詳細(xì)的代碼示例供大家作為參考,感興趣的同學(xué)可以參考閱讀一下2023-08-08
Vuejs如何通過(guò)Axios請(qǐng)求數(shù)據(jù)
這篇文章主要介紹了Vuejs如何通過(guò)Axios請(qǐng)求數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
在vue中獲取微信支付code及code被占用問(wèn)題的解決方法
這篇文章主要介紹了在vue中獲取微信支付code及code被占用問(wèn)題的解決方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-04-04

