vue横向滑动实现
Vue 横向滑动实现方法
使用 CSS Flexbox 布局
通过 display: flex 和 overflow-x: auto 实现横向滚动容器,子元素设置 flex-shrink: 0 防止挤压。
<template>
<div class="horizontal-scroll">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
</template>
<style scoped>
.horizontal-scroll {
display: flex;
overflow-x: auto;
gap: 16px; /* 可选间距 */
padding: 8px 0;
}
.scroll-item {
flex-shrink: 0;
width: 120px; /* 固定宽度示例 */
}
</style>
使用第三方库(如 Swiper)
安装 Swiper 库后,可直接实现丰富的滑动效果,支持触摸和响应式。
npm install swiper@8
<template>
<swiper :slides-per-view="3" :space-between="20">
<swiper-slide v-for="item in items" :key="item.id">
{{ item.content }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
export default {
components: { Swiper, SwiperSlide }
};
</script>
监听滚动事件实现动态效果
结合 @scroll 事件和 ref 实现滚动交互逻辑,如显示/隐藏导航按钮。
<template>
<div ref="scrollContainer" class="scroll-container" @scroll="handleScroll">
<!-- 内容 -->
</div>
<button v-if="showLeftNav" @click="scrollLeft">←</button>
</template>
<script>
export default {
methods: {
scrollLeft() {
this.$refs.scrollContainer.scrollBy({ left: -200, behavior: 'smooth' });
},
handleScroll() {
this.showLeftNav = this.$refs.scrollContainer.scrollLeft > 0;
}
}
};
</script>
响应式宽度调整
通过计算属性动态设置子元素宽度,适应不同屏幕尺寸。

computed: {
itemWidth() {
return window.innerWidth < 768 ? '100px' : '150px';
}
}
注意事项
- 移动端需添加
-webkit-overflow-scrolling: touch提升滚动流畅度。 - 避免在滚动容器内使用过多复杂元素,可能影响性能。
- 若需无限滚动,可结合虚拟滚动技术(如
vue-virtual-scroller)。






