vue实现滚动tab
实现滚动 Tab 的基本思路
滚动 Tab 通常用于横向导航栏,当内容超出容器宽度时支持左右滑动。核心逻辑是通过监听滚动事件或手动滑动操作,动态调整 Tab 的位置。
使用 CSS 实现基础滚动
通过 white-space: nowrap 和 overflow-x: auto 实现横向滚动:
<div class="scroll-tab-container">
<div class="tab-list">
<div class="tab-item" v-for="item in tabs" :key="item.id">{{ item.name }}</div>
</div>
</div>
.scroll-tab-container {
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch; /* 平滑滚动 */
}
.tab-list {
display: flex;
white-space: nowrap;
}
.tab-item {
padding: 8px 16px;
flex-shrink: 0;
}
动态计算滚动位置
通过 ref 获取 DOM 并计算滚动位置,实现主动滚动到指定 Tab:

<div class="scroll-tab-container" ref="container">
<div class="tab-list" ref="tabList">
<div class="tab-item"
v-for="item in tabs"
:key="item.id"
@click="scrollToTab(item.id)"
:ref="'tab_' + item.id">
{{ item.name }}
</div>
</div>
</div>
methods: {
scrollToTab(tabId) {
const container = this.$refs.container;
const tabElement = this.$refs[`tab_${tabId}`][0];
const containerWidth = container.offsetWidth;
const tabLeft = tabElement.offsetLeft;
const tabWidth = tabElement.offsetWidth;
container.scrollTo({
left: tabLeft - (containerWidth - tabWidth) / 2,
behavior: 'smooth'
});
}
}
添加滚动指示器
通过监听滚动事件,显示左右滚动箭头:
<button @click="scroll(-100)" :disabled="!canScrollLeft">←</button>
<div class="scroll-tab-container" @scroll="handleScroll">
<!-- Tab 内容 -->
</div>
<button @click="scroll(100)" :disabled="!canScrollRight">→</button>
data() {
return {
canScrollLeft: false,
canScrollRight: false
}
},
methods: {
handleScroll() {
const container = this.$refs.container;
this.canScrollLeft = container.scrollLeft > 0;
this.canScrollRight =
container.scrollLeft + container.offsetWidth < container.scrollWidth;
},
scroll(offset) {
this.$refs.container.scrollBy({
left: offset,
behavior: 'smooth'
});
}
}
使用第三方库
对于复杂需求,可考虑以下库:

vue-tabs:提供预置的滚动 Tab 功能swiper/vue:实现触摸友好的滑动效果
安装 Swiper 示例:
npm install swiper
<swiper :slides-per-view="'auto'" :space-between="10">
<swiper-slide v-for="item in tabs" :key="item.id">
{{ item.name }}
</swiper-slide>
</swiper>
响应式处理
根据窗口大小调整显示的 Tab 数量:
mounted() {
window.addEventListener('resize', this.updateVisibleTabs);
},
beforeDestroy() {
window.removeEventListener('resize', this.updateVisibleTabs);
},
methods: {
updateVisibleTabs() {
const containerWidth = this.$refs.container.offsetWidth;
// 根据容器宽度计算可显示的 Tab 数量
}
}






