vue实现滑动tab
实现滑动 Tab 的基本思路
在 Vue 中实现滑动 Tab 可以通过结合 v-for 动态渲染 Tab 标签,使用 CSS 控制滑动效果,并通过 Vue 的响应式数据管理当前选中状态。核心在于动态计算滑动条的偏移位置和宽度。

基础代码结构
<template>
<div class="sliding-tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab-item"
:class="{ 'active': activeIndex === index }"
@click="switchTab(index)"
>
{{ tab.label }}
</div>
<div class="slider" :style="sliderStyle"></div>
</div>
<div class="tabs-content">
<div v-for="(tab, index) in tabs" :key="index" v-show="activeIndex === index">
{{ tab.content }}
</div>
</div>
</div>
</template>
数据与样式定义
<script>
export default {
data() {
return {
tabs: [
{ label: 'Tab 1', content: 'Content 1' },
{ label: 'Tab 2', content: 'Content 2' },
{ label: 'Tab 3', content: 'Content 3' }
],
activeIndex: 0,
sliderWidth: 0,
sliderOffset: 0
};
},
computed: {
sliderStyle() {
return {
width: `${this.sliderWidth}px`,
transform: `translateX(${this.sliderOffset}px)`
};
}
},
methods: {
switchTab(index) {
this.activeIndex = index;
this.updateSliderPosition();
},
updateSliderPosition() {
const tabElements = document.querySelectorAll('.tab-item');
if (tabElements[this.activeIndex]) {
this.sliderWidth = tabElements[this.activeIndex].offsetWidth;
this.sliderOffset = tabElements[this.activeIndex].offsetLeft;
}
}
},
mounted() {
this.updateSliderPosition();
window.addEventListener('resize', this.updateSliderPosition);
},
beforeDestroy() {
window.removeEventListener('resize', this.updateSliderPosition);
}
};
</script>
CSS 样式
<style scoped>
.sliding-tabs {
width: 100%;
}
.tabs-header {
display: flex;
position: relative;
border-bottom: 1px solid #eee;
}
.tab-item {
padding: 10px 20px;
cursor: pointer;
transition: color 0.3s;
}
.tab-item.active {
color: #42b983;
}
.slider {
position: absolute;
bottom: 0;
left: 0;
height: 2px;
background-color: #42b983;
transition: all 0.3s ease;
}
.tabs-content {
padding: 20px 0;
}
</style>
动态滑动实现说明
- 滑动条计算:通过
offsetWidth和offsetLeft动态获取当前选中 Tab 的宽度和偏移位置,赋值给sliderWidth和sliderOffset。 - 响应式更新:监听窗口
resize事件,确保滑动条位置随窗口大小变化重新计算。 - 过渡动画:CSS 的
transition属性为滑动条添加平滑移动效果。
扩展功能
- 动态 Tab 数据:通过接口异步加载
tabs数据,需在数据更新后调用this.$nextTick(() => this.updateSliderPosition())。 - 滚动支持:若 Tab 数量过多,可为
tabs-header添加横向滚动条(overflow-x: auto),并动态调整滑动条位置。
注意事项
- 确保 Tab 项的宽度一致或动态计算,避免滑动条宽度跳动。
- 组件销毁时移除事件监听,避免内存泄漏。






