1. 需求:页面顶部展示n个小图标。当选中某个图标时,下方视图会相应切换;反之,当滑动下方视图时,顶部选中的图标也会同步更新。
2. 思路: 上方scroll-view 区域渲染图标,并且可左右滑动,下方使用swiper可以左右滑动。
3. 代码实现
- 上方图标渲染
(1)将 scroll-x 属性设为 true 以启用左右滑动功能,同时动态绑定 scroll-left 属性实现上下联动滑动效果。
bash
<scroll-view scroll-x="true" class="view_top" :scroll-left="scrollWidth" enhanced="true" :scroll-with-animation="true" :show-scrollbar="false">
<view class="icons">
<view class="icon_view" v-for="(item1, index1) in list1" :key='index1' :id="'tabNum' + index1">
<image class="icon" :src="'item1.url'" mode="aspectFit" v-if="tIndex != index1" @click="chooseIcon(index1)"></image>
<image class="icon" :src="'item1.url" mode="aspectFit" v-if="tIndex == index1"></image>
<text class="icon_name" :class="taskIndex == index1 ? 'icon_name_select' : ''">{{item1.name}}</text>
</view>
</view>
</scroll-view>
(2)点击图标切换下方视图 chooseIcon
bash
chooseIcon(index){
this.tIndex = index
this.tabCurrent = 'tabNum' + index
this.getScrollWidth(index)
},
(3)css样式
bash
.view_top{
white-space: nowrap;
width: 100%;
height: 15vh;
margin-top: 4vh;
}
.icons{
height: 15vh;
}
.icon{
width: 22vw;
height: 10vh;
}
.icon_name{
text-align: center;
width: 22vw;
display: block;
font-size: 22rpx;
}
.icon_name_select{
color: black;
}
.icon_view{
display: inline-block;
white-space: nowrap;
position: relative;
}
- 下方视图渲染
(1)current绑定角标,@change监听滑动操作
bash
<swiper class="Swiper" :current="tIndex" @change="swiperChange">
<swiper-item class="Swiper_item" v-for="(item2, index2) in List2" :key='index2'>
<view class="Swiper_item_view"></view>
</swiper-item>
</swiper>
(2)滑动监听函数 swiperChange
bash
swiperChange(e) {
let index = e.detail.current
this.chooseIcon(index)
},
(3)scrollWidth计算横向滚动参数,为确保位置的精准性,将vw转化为px
bash
getScrollWidth(index) {
var vw = (index )*22 /100 * this.vwsize;
var data = vw + 'px';
this.contentScrollW = data;
}
(4)css样式
css
.Swiper_item{
display: flex;
flex-direction: column;
background-image: url('url');
background-size: cover;
background-position: center;
overflow: auto;
height: 100%;
width: 100%;
}
.Swiper_item_view{
display: flex;
flex-direction: column;
overflow: auto;
height: 100%;
width: 100%;
position: relative;
}
以上是 uniapp 小程序实现上下轮播联动功能的具体方法。