小程序也可以瀑布流,走起

689 阅读1分钟

首先

本文采用mpvue框架写小程序。原生爱好者自己翻译一下,原理差不多。基本原理就是,对于两列瀑布流,左右两列分别对应一个数组,每次更新瀑布流的时候实时计算对应数组的高度就可以。

代码

data () {
    return {
        itemsLeft : [],
        itemsRight : []
    }
}
// 计算数组高度
  getArraysHeight (arrays) {
      if (!arrays) return
      return arrays.reduce((total, item) => {
        return total + item.srcHeight / item.srcWidth 
      }, 0)
    },
    
// 计算数组的items放入哪个数组
pushItem (arrays) {
      for (let item of arrays) {
        this.getArraysHeight(this.itemsLeft) <= this.getArraysHeight(this.itemsRight) ? this.itemsLeft.push(item) : this.itemsRight.push(item)
      }
    },