vue 使用css 实现动态tab切换效果

先贴出代码:
 
<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当前的减去移动了多少,就对了,我通过了一个方法计算出来了,也很容易,然后就是,点击当前他肯定是不会动的,就是什么也不执行,我上面方法有写,大家可以看一下。
 
百度上看了一些别人写的,感觉都不是我想要的,我就自己写这么一个,当然现在有很多插件直接可以实现, 希望我这个思路也可以帮助到大家

posted @ 2020-03-10 17:10  _你的影子  阅读(1754)  评论(0编辑  收藏  举报