效果图
思路
滑块位置=居中的位置+每一项的宽度乘以当前索引
组件代码
<template>
<view>
<view class="tab-box">
<view class="active-bar" :style="{'transform':`translateX(${translateX}px)`,'width':`${width}px`,'height':`${drawHeight}px`}"></view>
<view :class="['tab-item',activeIndex === index ?'active':'']" v-for="(item,index) in tab" :key="index" @click="handleChange(item,index)">{{ item }}</view>
</view>
<!-- 自提 -->
<slot name="pick" v-if="activeIndex===0"></slot>
<!-- 配送 -->
<slot name="dispatching" v-if="activeIndex===1"></slot>
</view>
</template>
<script>
/**
* activeIndex 选中索引
* tab tab 数据 字符串数组
* drawWidth 底部滑条宽度
* drawHeight 底部滑条高度
*/
export default {
props:{
activeIndex:{
type: Number,
default: -1,
},
tab:{
type:Array,
default:[]
},
drawWidth:{
type:String,
default:''
},
drawHeight:{
type:String,
default:'1'
}
},
computed:{
//滑动条的宽度
width(){
if(this.drawWidth){
return this.drawWidth
}else{
return this.tabWidth/this.tab.length
}
}
},
data(){
return {
translateX:0,
active:this.activeIndex,
//tab的宽度
tabWidth:0
}
},
created(){
this.getWidth()
if (this.drawWidth) {
let query = uni.createSelectorQuery().in(this);
//选择id
let that = this;
query.select('.tab-box').boundingClientRect(function(rect) {
that.translateX = (rect.width / that.tab.length)/2-Number(that.width)/2
}).exec()
}
},
methods:{
handleChange(item,index){
if(this.drawWidth){
let query = uni.createSelectorQuery().in(this);
//选择id
let that = this;
query.select('.tab-box').boundingClientRect(function (rect) {
// 滑块位置=居中的位置+每一项的宽度乘以当前索引
let width=(rect.width / that.tab.length)/2 - Number(that.width)/2
that.translateX=width+(rect.width / that.tab.length)*index
}).exec()
}else{
this.translateX=index*this.width
}
this.$emit('update:activeIndex',index)
this.$emit('change',item)
},
getWidth(){
let query = uni.createSelectorQuery().in(this);;
//选择id
let that = this;
query.select('.tab-box').boundingClientRect(function (rect) {
that.tabWidth=rect.width
}).exec()
}
}
}
</script>
<style lang="scss" scoped>
.tab-box{
display: flex;
box-sizing: border-box;
height: 86rpx;
position: relative;
background-color: #fff;
.active-bar{
position: absolute;
bottom: 0;
left: 0;
height: 3rpx;
background-color: #FF4B40;
transition: all .3s
}
.tab-item{
font-size: 30rpx;
font-family: PingFang SC;
font-weight: bold;
color: #000000;
line-height: 86rpx;
flex: 1;
text-align: center;
border-bottom: 1rpx solid #EEEEEE;
}
.active{
color:#FF4B40;
}
}
</style>