scroll-view

scroll-x					允许横向滚动
scroll-top					设置横向滚动条位置
scroll-with-animation		在设置滚动条位置时使用动画过渡

1、注意需要在data中给.box一个默认的宽度,因为css设置的是display: flex;
2、加上默认宽度后onLoad中可以根据数据tabTopList数据个数,计算出每个itemWidth的宽度,总宽度totalWidth

<view class="tabTop">
	<scroll-view 
		scroll-x="true" 
		:scroll-left="scrollLeft" 
		:scroll-with-animation="true">
		<view class="box" :style="{'width':totalWidth+'px'}">
			<view 
				class="tabTopItem" 
				v-for="(item,index) in 10" 
				:key="index" 
				:class="{'ac':tabTopCurrent == index}" @click="tabTopChange(index)">
				测试{{item.name}}仓
				<image src="../../static/icon/87.png" mode="" class="tips" v-if="index == 0"></image>
			</view>
		</view>
	</scroll-view>
</view>
<script>
	export default {
		data() {
			return {
				itemWidth:0,//每个item的宽度
				totalWidth:10000,//设置一个默认总宽度
				scrollLeft:0,//滑动距离
				tabTopList: [],
				tabTopCurrent: 0,
			}
		}
		onLoad() {
			/*
				计算总宽度和每个item的宽度
				item宽度 = 自身宽度 + 8px右边距
				总宽度 = item个数 * 每个item的宽度
			*/
			this.$nextTick(()=>{
				let dom = uni.createSelectorQuery().select(".tabTopItem");
				dom.boundingClientRect((data)=> {
					let num = this.tabTopList.length;
					this.itemWidth = data.width+8;
					this.totalWidth = num*this.itemWidth;
				}).exec()
			})
		},
		methods: {
			// 点击tab切换高亮,并进行滑动,(index-1)是为了点击项显示在第二栏的位置
			tabTopChange(index){
				this.tabTopCurrent = index;
				this.scrollLeft = this.itemWidth*(index-1);
			},
		}
	}
.tabTop{
	width: 702rpx;
	background: #FFFFFF;
	height: 90rpx;
	margin: auto;
	/* 隐藏滚动条样式 */
	::-webkit-scrollbar {
		width: 0;
		height: 0;
	}
	.box{
		display: flex;
		align-items: center;
		.tabTopItem{
			text-align: center;
			width: 168rpx;
			height: 90rpx;
			line-height: 90rpx;
			background: #F6F7FB;
			font-size: 28rpx;
			color: #8D9199;
			margin-right: 8px;
			position: relative;
			.tips{
				position: absolute;
				right: 0;
				top: 0;
				width: 72rpx;
				height: 28rpx;
			}
		}
		.ac{
			font-size: 30rpx;
			background: #fff;
			color: #17181B;
		}
	}
}

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐