下面代码是结合scroll和swiper组合使用,实现tab和内容的切换,
scroll是横向滚动,
<template>
<view class="content">
<view>
<scroll-view
class="scroll-view_H"
scroll-x="true"
@scroll="scroll"
scroll-left="120"
>
<view
id="demo1"
class="scroll-view-item_H uni-bg-red"
v-for="(item, index) in tab"
:key="index"
@click="scroll(index)"
><view :class="tabIndex == index ? 'active' : ''">
{{ item }}
</view></view
>
</scroll-view>
<swiper @change="handle_swiperChange" :current="tabIndex" next-margin="100rpx">
<swiper-item
class="swiper"
v-for="(item, index) in tab"
:key="index"
>
{{ item }}
</swiper-item>
</swiper>
</view>
</view>
</template>
<script>
export default {
data() {
return {
tabIndex: 0,
tab: ["热搜榜", "视频榜", "博客榜"],
};
},
methods: {
scroll(i) {
this.tabIndex = i;
},
handle_swiperChange(e) {
console.log(e);
this.tabIndex=e.detail.current
},
},
};
</script>
<style scoped lang='less'>
.content {
height: 100vw;
.scroll-view_H {
white-space: nowrap;
}
.uni-bg-red {
height: 50rpx;
display: inline-block;
margin-right: 30rpx;
}
.uni-bg-green {
height: 50rpx;
display: inline-block;
margin-right: 30rpx;
}
.uni-bg-blue {
height: 50rpx;
display: inline-block;
}
}
.swiper {
width: 90rpx;
}
.active {
color: red;
}
</style>
然后是使用中遇到的坑:
1.首先需要给scroll-view 设置 white-space: nowrap;
2.需要给scroll内的子元素添加: display: inline-block;height:高度