小程序返回的数据如何在swiper做分组滑动

接口:/api/users
返回:data:[{id: "1", title: "小明", img: "xxx.com/1.jpg"}, {id: "2", title: "小明2", img: "xxx.com/1.jpg"},{id: "3", title: "小明3", img: "xxx.com/3.jpg"}]
数据大概18条,我只打了3条

分组放到小程序的swiper里的 swiper-item做页面切换

9条数据为一组, 把数据放到 swiper-item
<block wx:for="{{data}}"><swiper-item><view>{{item.title}}</view></swiper-item></block>

怎么样%9循环出两个swiper-item呢?

阅读 3.6k
2 个回答

自己把数据封装好再循环就好啦

const test = [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
const i = Math.floor(index / length);
let result = []
result[0]= test.slice(0,i-1);
result[1]= test.slice(i-1,test.length-1);
//最后拿resul循环即可

解决

      const test = [1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
      const func = function (arry, length) {
        let result = []
        arry.forEach((ele, index) => {
          const i = Math.floor(index / length)
          console.log(i)
          if (!result[i]) {
            result[i] = []
          }
        })
        return result
      }
      console.log(func(test, 5))

原理

就是除法运算,根据需要的长度来组合二维数组
有点类似于九九乘法表

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题