先貼出代碼:
<template>
<view class="m-wrap">
<view class="m-content">
<view class="m-tab">
<view class="m-tab-item" :class="tabIndex === index ? 'm-tab-item-active' : ''" v-for="(item, index) in tabList" :key="index" @click="toggleTab(index)">{{item}}</view>
<view class="tab-line" :style="{left: number + 'rpx'}"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
tabIndex: 0,
tabList: ['自選', '市值', '大盤', '排行'],
number: 0
}
},
methods: {
toggleTab(index) {
if (this.tabIndex < index) {
console.log(index)
this.number = index * 172
} else {
this.number = this.number - ((this.tabIndex-index) * 172)
}
this.tabIndex = index
}
}
}
</script>
<style scoped>
.m-content { margin-top: 35rpx;}
.m-tab { position: relative; margin: 0 54rpx; display: flex; align-items: center; justify-content: space-between;}
.m-tab-item { width: 125rpx; color: #8D8EA6; font-size: 26rpx; text-align: center; padding-bottom: 15rpx;}
.m-tab-item-active {color: #00F1B7;}
.tab-line {height: 4rpx; width: 125rpx; background: #00F1B7; position: absolute; bottom: 0; left: 0; transition: all 0.3s ease;}
</style>

點擊之后,下划線會滑動到當前點擊的item下面
布局我使用list循環,然后這個是一個下划線滑動的效果,下划線定位,首先講幾個主要的思路:
1. 我需要控制下滑線移動,定位,通過css3控制他的過渡效果,高度固定的只需要控制 left 或者 right 就行,所以我需要定義一個動態的style
2. js方法點擊,點擊當前某個,然后下划線定位到他的下面,這是我想要的效果,然后我開始嘗試下划線的left是多少,一般tab都是對稱的也就是每個寬度,和間距都是一樣的,第一個比如是0,第二個是50,那么第三個肯定就是150,通過這個規律計算一下left是多少,那么向右點擊就差不多可以實現了,然后肯定還有向左,向左肯定就是left當前的減去移動了多少,就對了,我通過了一個方法計算出來了,也很容易,然后就是,點擊當前他肯定是不會動的,就是什么也不執行,我上面方法有寫,大家可以看一下。
百度上看了一些別人寫的,感覺都不是我想要的,我就自己寫這么一個,當然現在有很多插件直接可以實現, 希望我這個思路也可以幫助到大家