在开发H5的时候,结合Vant组件的轮播组件Swipe实现如下功能。我们查阅vant组件库官方文档可以得知,每个SwipeItem组件代表一个卡片,实现的是每屏展示单张图片或者单个div轮播方式,具体可以查阅:Vant 2 - 轻量、可靠的移动端组件库 (youzan.github.io)
这里的需求是要实现每屏展示多张图片或者说多个div卡片,那么这个时候就要考虑到多维数组嵌套循环,也就是两层循环。
通常情况下,后台返回的数据一般都是一维数组结构,那么这个时候我们就需要自行处理数组结构,将一维数组转换为二维数组。我这里封装的一个数组转换方法如下:
- /**
- * 将一维数组转成二维数组
- * arr:一维数组
- * num:二维数组的长度
- * 返回值:二维数组
- * */
- changeArr(arr, num) {
- let newArr = []
- for (let i = 0; i < arr.length; i += num) {
- newArr.push(arr.slice(i, i + num))
- }
- return newArr
- }
数据结构
- lightModeList: [
- {
- mode_name: '温馨',
- id: 0,
- },
- {
- mode_name: '浪漫',
- id: 1,
- },
- {
- mode_name: '起夜',
- id: 2,
- },
- {
- mode_name: '标准',
- id: 3,
- },
- {
- mode_name: '睡眠',
- id: 4,
- }
- ]
由于我这里还有一个需求,就是图标数据后台不返回,需要H5本地保存并进行匹配,所以我这里还会用到另外一个方法进行图片字段的处理:
- /**
- * 给列表数据加上图标匹配
- * modeList:列表数据
- * 返回值:加上图标匹配的列表数据
- * */
- addIconToModeList(modeList) {
- let list = modeList
- for (let i = 0; i < list.length; i++) {
- list[i].icon = list[i].id + ''
- list[i].selectIcon = list[i].id + '_select'
- }
- return list
- },
数据转换
- ...
- this.newLightModeList = this.$threeInchCommon.addIconToModeList(this.lightModeList)
- this.newLightModeList = this.$threeInchCommon.changeArr(this.newLightModeList, 3)
- ...
页面显示
-
- <div class="my-swipe">
- <div class="swipe-title">灯光模式div>
- <van-swipe :lazy-render="true" indicator-color="#FFBD4F">
- <van-swipe-item v-for="(itemList, keyIndex) in newLightModeList" :key="keyIndex" class="swiper-item-box">
- <div v-for="(item,index) in itemList" :key="index" class="swiper-item" @click="selectMode(item)">
- <div class="swiper-item-img">
- <img :src="selectLightValue===item.id?getIconImg(item.selectIcon):getIconImg(item.icon">
- <img :src="selectLightValue===item.id?getIconImg(item.selectIcon):getIconImg(item.icon">
- div>
- <div class="swiper-item-text">
- <p>{{ item.mode_name }}
- div>
- div>
- van-swipe-item>
- van-swipe>
- div>
样式
- .my-swipe{
- width: 100%;
- margin: 15px 0;
- background: #fff;
- padding: 10px 0;
- border-radius: 15px;
- .swipe-title{
- font-size: 16px;
- color: #333;
- padding: 10px 0;
- margin-left: 10px;
- font-weight: bold;
- }
- .swiper-item-box{
- display: flex;
- align-items:center;
- .swiper-item{
- display: flex;
- flex-direction: column;
- align-items:center;
- width: 33%;
- .swiper-item-img:active{
- scale: 1.1;
- }
- .swiper-item-img{
- width: 40px;
- height: 40px;
- img{
- width: 100%;
- height: 100%;
- }
- }
- .swiper-item-text{
- font-size: 14px;
- color: #666;
- }
- }
- }
- }