How to realize the waterfall function in the figure below?
think
The core of the waterfall is to find the smallest height in each column and add data to the current column.
The data in the picture can be simplified into the following format
const list = [
{title: '名字1', content: ['a', 'b', 'c', 'd']},
{title: '名字2', content: ['a', 'b', 'c']}
{title: '名字3', content: ['a', 'b']}
]
accomplish
The data shown in the figure is in four columns, so we need to initialize a four-column array of data.
At the same time, an array is required to retain the current height of each column, which is also initialized to 0.
const classifyColumns = [[], [], [], []]
const colHeight = [0, 0, 0, 0]
The misunderstanding at the beginning was that I wanted to automatically obtain the height of the rendered card. At this time, the data has not been sorted out, which is obviously unreasonable.
Observing the style in the picture, we can see that the height of each item is actually fixed and can be calculated.
list.forEach((item) => {
// 获取每列最小高度
const minColHeight = Math.min(...colHeight)
// 获取当前最小高度的列
const rowIndex = colHeight.indexOf(minColHeight)
// 将数据push到当前最小列中
classifyColumns[rowIndex].push(item)
// 更新当前列的高度
colHeight[rowIndex] = colHeight[rowIndex] + this.calcWaterfallHeight(item)
})
// calcWaterfallHeight 根据当前item计算当前卡片高度
Finally, use classifyColumns
render the data.
Final code
computed: {
// 瀑布流数据处理
classifyColumns () {
const colHeight = [0, 0, 0, 0]
const classifyColumns = [[], [], [], []]
this.list.forEach((item) => {
const minColHeight = Math.min(...colHeight)
const rowIndex = colHeight.indexOf(minColHeight)
classifyColumns[rowIndex].push(item)
colHeight[rowIndex] = colHeight[rowIndex] + this.calcWaterfallHeight(item)
})
return classifyColumns
}
},
`
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。