uniapp使用scroll-view与swiper组件实现tab滑动切换页面需要注意的问题
效果图:
tab栏可以滑动,切换页面跟随tab栏同步滑动。这里需要注意的是使用swiper组件时,它会有一个默认的高度,你必须动态的获取数据列表的高度覆盖原来的默认高度。
下面是代码
html
<template>
<view>
<scroll-view class="scroll1" scroll-x="true">
<view :class="currentTab==index ? 'select' : ''" :data-current="index" @click="swichNav" v-for="(item,index) in scoll"
:key='index'>{{item.txt}}
</view>
</scroll-view>
<swiper :current="currentTab" @change="bindChange" class='swp' :style="{height:aheight?aheight+'px':'auto'}">
<swiper-item>
<view class="list-item">
<view class="list" v-for="(item,index) in list" :key='index'>
<view class="list-img">
<image :src="item.imgb" mode=""></image>
</view>
<view class="list-con">
<view>{{item.tit}}</view>
<view class="list-foot">
<view>
<image src="../../static/images/user.png" mode="" class="user"></image>
<view class="username">{{item.user}}</view>
</view>
<view>
<image src="../../static/images/love.png" mode="" class="like"></image>
<view class="likenum">{{item.like}}</view>
</view>
</view>
</view>
</view>
</view>
</swiper-item>
<swiper-item>玻尿酸</swiper-item>
<swiper-item>水光针</swiper-item>
<swiper-item>眼部</swiper-item>
<swiper-item>鼻部</swiper-item>
<swiper-item>瘦身塑型</swiper-item>
</swiper>
</view>
</template>
js
<script>
export default {
data() {
return {
currentTab: 0,
aheight: '',
scoll: [{
txt: '精选'
}, {
txt: '玻尿酸'
}, {
txt: '水光针'
}, {
txt: '眼部'
}, {
txt: '鼻部'
}, {
txt: '瘦身塑型'
}],
}
}
onShow(){
// 动态获取滑动页面高度
const query = uni.createSelectorQuery().in(this);
query.select('.list').boundingClientRect(data => {
this.aheight = data.height
}).exec();
},
methods: {
// 滑动页面同步tab栏
bindChange: function(e) {
this.currentTab = e.detail.current
},
//点击tab切换
swichNav: function(e) {
var that = this;
if (this.currentTab === e.target.dataset.current) {
return false;
} else {
this.currentTab = e.target.dataset.current
}
}
}
}
<script>
css
<style scoped lang="less">
.scroll1 {
width: 100%;
white-space: nowrap;
padding: 25rpx 0;
& view {
white-space: normal;
display: inline-block;
}
& view:before {
content: '|';
color: #f4f4f4;
margin: 0 30rpx;
}
& view:first-child:before {
display: none;
}
.select {
color: #fb6583;
}
}
.list-item {
overflow: hidden;
margin-left: -1%;
.list {
float: left;
width: 48%;
margin:20rpx 0 0 1%;
border: solid 1px #eaeaea;
background-color: #ffffff;
border-radius: 12rpx;
.list-img {
image {
object-fit: fill;
width: 100%;
border-top-left-radius: 12rpx;
border-top-right-radius: 12rpx;
height: 364rpx;
}
}
.list-con {
padding: 15rpx;
.list-foot {
margin-top: 20rpx;
display: flex;
justify-content: space-between;
align-items: center;
&>view {
font-size: 26rpx;
display: flex;
align-items: center;
}
.username {
color: #999999;
margin-left: 10rpx;
width: 150rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.user {
width: 50rpx;
height: 50rpx;
}
.likenum {
color: #333333;
margin-left: 10rpx;
}
.like {
width: 28rpx;
height: 28rpx;
}
}
}
}
}
</style>
作者:Vam的金豆之路
主要领域:前端开发
我的微信:maomin9761
微信公众号:前端历劫之路