因?yàn)闀r(shí)常需要用到瀑布流布局,但是在github上找到的vue-waterfall組件需要自己定義內(nèi)容的長寬(大概是這個(gè)意思系瓢?我沒有看懂那個(gè)的用法)蟹地,而且和自己的項(xiàng)目的內(nèi)容布局有些差異于是就自己寫一個(gè)基于vue的瀑布流布局。在此記錄一下思考過程和實(shí)現(xiàn)方法乎婿。
基本思想
如下圖實(shí)現(xiàn)的布局:
其實(shí)很容易就想到了ul肠阱,我們想要幾列布局就寫幾個(gè)ul就好了票唆。
但是我們?cè)趺慈ネ鵸l里面填充內(nèi)容呢?因?yàn)槲易约赫J(rèn)為vuejs的思想就是通過操作數(shù)據(jù)來實(shí)現(xiàn)布局的變化屹徘,那么只需要知道哪些數(shù)據(jù)放在左邊走趋,哪些在右邊就可以了。
代碼實(shí)現(xiàn)
根據(jù)上述思想定義一些數(shù)據(jù)如下:
data () {
return {
data: [], // 在created的時(shí)候獲取所有要展示的數(shù)據(jù)
leftItems: [], // 存放左邊ul里面要展示的數(shù)據(jù)
rightItems: [] // 存放右邊ul里面要展示的數(shù)據(jù)
}
}
首先我們將所有要展示的數(shù)據(jù)都存放在data數(shù)組里面噪伊,然后就是不停的吧data數(shù)組里面的數(shù)據(jù)一個(gè)一個(gè)的取出放在leftItems或者rightItems里面就可以渲染出頁面了簿煌。這里要解決的問題是 怎么選擇左邊還是右邊?我想到了之前記錄的那篇 Vue的生命周期和nextTick ()文章中解決了顯示數(shù)據(jù)的問題鉴吹,那么只要遞歸地比較左邊ul和右邊ul的可視高度姨伟,然后再把內(nèi)容放在高度小的一邊即可,思路清晰之后豆励,代碼的實(shí)現(xiàn)就變得簡單直觀起來:
mounted () {
// TODO GET DISPLAY_DATA
this.updateWaterfall()
},
methods: {
updateWaterfall () {
const leftHeight = this.$refs.left.clientHeight
const rightHeight = this.$refs.right.clientHeight
let item = this.data.shift()
if (item == null) {
return
}
if (leftHeight <= rightHeight) {
this.leftItems.push(item)
}
else {
this.rightItems.push(item)
}
this.$nextTick(function () {
this.updateWaterfall()
})
}
}
最后放上我所有的代碼:
<template>
<div class="waterfall-wrapper">
<ul class="left-waterfall" ref="left">
<li class="item" v-for="(item, index) in leftItems" v-bind:style=" {height:item.height+'px'}">{{ index }}</li>
</ul>
<ul class="right-waterfall" ref="right">
<li class="item" v-for="(item, index) in rightItems" v-bind:style=" {height:item.height+'px'}">{{ index }}</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
data: [
{
height: 100
},
{
height: 110
},
{
height: 150
},
{
height: 200
},
{
height: 300
},
{
height: 100
},{
height: 222
},{
height: 111
},{
height: 123
},{
height: 451
},
],
leftItems: [],
rightItems: []
}
},
mounted () {
// TODO GET DISPLAY_DATA
this.updateWaterfall()
},
methods: {
updateWaterfall () {
const leftHeight = this.$refs.left.clientHeight
const rightHeight = this.$refs.right.clientHeight
let item = this.data.shift()
console.log(leftHeight)
console.log(rightHeight)
if (item == null) {
return
}
if (leftHeight <= rightHeight) {
this.leftItems.push(item)
}
else {
this.rightItems.push(item)
}
this.$nextTick(function () {
this.updateWaterfall()
})
}
}
}
</script>
<style scoped>
ul {
width: 40%
}
ul.left-waterfall {
float: left;
}
ul.right-waterfall {
float: right;
}
li.item {
width: 100%;
background-color: aqua;
margin: 10px;
}
</style>
關(guān)于以上代碼中的nextTick的使用和作用還煩請(qǐng)移步我的另一篇文章:Vue的生命周期和nextTick ()
寫在最后
最近開始都特別忙夺荒,而且上一兩周的時(shí)間也出現(xiàn)了厭惡工作的情緒,好在及時(shí)調(diào)整過來,對(duì)于代碼和生活都不是任務(wù)而是應(yīng)該認(rèn)真尊重和對(duì)待的兩件事般堆。還是希望這往后的一年自己能對(duì)得起自己在孝,不辜負(fù)大部分人吧诚啃。