<template>
<!-- tab切换 -->
<div class="my-tab" ref="myTabRef">
<div class="my-tab-item" v-for="(item, index) in tabs" :ref="`tab${item.name}Ref`" :class="{ active: item.name === activeItem }" :key="index">
<div class="my-tab-text" @click="tabClick(item)">{{ item.label }}</div>
</div>
</div>
</template>
<script>
export default {
name: 'my-tab',
data() {
return {
activeItem: 'tabOne',
tabs: [
{
name: 'tabOne',
label: 'tab切换显示1',
},
{
name: 'tabTwo',
label: 'tab切换显示2',
},
{
name: 'tabThree',
label: 'tab切换显示3',
},
{
name: 'tabFour',
label: 'tab切换显示4',
},
{
name: 'tabFive',
label: 'tab切换显示5',
},
{
name: 'tabSix',
label: 'tab切换显示6',
},
{
name: 'tabSeven',
label: 'tab切换显示7',
},
{
name: 'tabEight',
label: 'tab切换显示8',
},
],
};
},
methods: {
// tab点击
tabClick(item) {
this.activeItem = item.name;
// 触发滑动方法
this.scrollLeftTo(item.name);
},
// 滑动
scrollLeftTo(name) {
const ref = `tab${name}Ref`;
// 获取myTabRef的DOM元素,即类名为my-tab的标签
const nav = this.$refs.myTabRef;
// 获取当前点击的某一个tab的的DOM元素,即类名为my-tab-item的标签
const title = this.$refs[ref][0];
console.log('nav.offsetWidth' + nav.offsetWidth)
console.log('title.offsetWidth' + title.offsetWidth)
// 计算位移偏差
const to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2;
nav.scrollLeft = to;
},
},
};
</script>
<style lang="scss">
.my-tab {
height: 88px;
background: #FFFFFF;
line-height: 88px;
display: flex;
overflow-x: scroll;
padding-right: 40px;
scroll-behavior: smooth; //平稳的滑动效果
.my-tab-item {
flex-shrink: 0;
padding: 0 24px;
color: #999999;
height: 88px;
text-align: center;
flex: 1 0 auto;
&.active {
color: #333333;
.my-tab-text {
position: relative;
&::after {
position: absolute;
left: 50%;
bottom: 0;
content: '';
width: 220px;
height: 4px;
background: linear-gradient(180deg, #649AFC 0%, #5180F4 100%);
opacity: 1;
border-radius: 2px;
transform: translateX(-50%);
}
}
}
}
}
// 隐藏滚动条
::-webkit-scrollbar {
height: 0;
width: 0;
color: transparent;
}
</style>