关于vue.js:卡片瀑布流实现

6次阅读

共计 1030 个字符,预计需要花费 3 分钟才能阅读完成。

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

思考

瀑布流的外围就是找每一列中最小的高度,给当前列增加数据。

图片中数据能够简化成如下格局

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

`

正文完
 0