likes
comments
collection
share

卡片瀑布流实现

作者站长头像
站长
· 阅读数 39

如何实现下图瀑布流功能?

卡片瀑布流实现

思考

瀑布流的核心就是找每一列中最小的高度,给当前列添加数据。

图片中数据可以简化成如下格式

const list = [
  {title: '名字1', content: ['a', 'b', 'c', 'd']},
  {title: '名字2', content: ['a', 'b', 'c']}
  {title: '名字3', content: ['a', 'b']}
]

实现

图中展示数据是四列,所以我们需要初始化一个四列数组数据。同时还需要一个数组保留每列当前的高度,也初始化为0。

const classifyColumns = [[], [], [], []]
const colHeight = [0, 0, 0, 0]

一开始的误区是想自动获取渲染后的卡片高度,这时候数据都还没整理,显然不合理。

观察图片中的样式可以看出来其实每项高度都是固定的,完全可以计算出来。

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计算当前卡片高度

最后使用 classifyColumns 渲染数据即可。

最终代码


  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
    }
  },

`

转载自:https://segmentfault.com/a/1190000041229368
评论
请登录