vue实现列表横向滑动
Vue 实现列表横向滑动的方法
使用 CSS Flexbox 和 overflow-x
通过 CSS Flexbox 布局结合 overflow-x: auto 可以实现横向滚动的列表。
<template>
<div class="scroll-container">
<div class="scroll-list">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.text }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
// 更多项目...
]
}
}
}
</script>
<style scoped>
.scroll-container {
width: 100%;
overflow-x: auto;
}
.scroll-list {
display: flex;
flex-wrap: nowrap;
gap: 10px;
padding: 10px 0;
}
.scroll-item {
flex: 0 0 auto;
width: 100px;
height: 100px;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用第三方库(如 vue-horizontal)
如果需要更复杂的功能,可以考虑使用专门的横向滚动库。

安装 vue-horizontal:

npm install vue-horizontal
使用示例:
<template>
<vue-horizontal>
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
</vue-horizontal>
</template>
<script>
import VueHorizontal from "vue-horizontal";
export default {
components: { VueHorizontal },
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
// 更多项目...
]
}
}
}
</script>
自定义触摸事件支持
如果需要支持触摸设备上的平滑滚动,可以添加 touch 事件处理。
<template>
<div
class="scroll-container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div class="scroll-list" ref="scrollList">
<!-- 列表内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
touchStartX: 0,
scrollLeft: 0
}
},
methods: {
handleTouchStart(e) {
this.touchStartX = e.touches[0].pageX
this.scrollLeft = this.$refs.scrollList.scrollLeft
},
handleTouchMove(e) {
const x = e.touches[0].pageX
const walk = (x - this.touchStartX) * 2
this.$refs.scrollList.scrollLeft = this.scrollLeft - walk
}
}
}
</script>
注意事项
- 确保容器有明确的宽度限制,否则滚动可能无法正常工作
- 移动设备上可能需要添加
-webkit-overflow-scrolling: touch来改善滚动体验 - 对于大量数据,考虑使用虚拟滚动技术优化性能
以上方法可以根据具体需求选择使用,CSS Flexbox 方案适合简单场景,而第三方库则提供更多高级功能。






