vue横向滑动实现
Vue 横向滑动实现方法
使用 CSS Flexbox 布局
在容器元素上设置 display: flex 和 overflow-x: auto,子元素设置 flex-shrink: 0 防止被压缩。
<div class="scroll-container">
<div v-for="item in items" :key="item.id" class="scroll-item">
{{ item.content }}
</div>
</div>
.scroll-container {
display: flex;
overflow-x: auto;
white-space: nowrap;
}
.scroll-item {
flex-shrink: 0;
width: 200px; /* 固定宽度 */
margin-right: 10px;
}
使用第三方库(如 vue-horizontal)
安装 vue-horizontal 库:
npm install vue-horizontal
使用示例:
<template>
<vue-horizontal>
<div v-for="item in items" :key="item.id">
{{ item.content }}
</div>
</vue-horizontal>
</template>
<script>
import VueHorizontal from "vue-horizontal";
export default {
components: { VueHorizontal },
data() {
return {
items: [...]
}
}
}
</script>
使用 touch 事件实现自定义滑动
通过监听 touch 事件计算滑动距离,结合 CSS transform 实现平滑滑动。
<div
class="custom-scroll"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${offsetX}px)` }"
>
<div v-for="item in items" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
export default {
data() {
return {
offsetX: 0,
startX: 0,
isDragging: false
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = true
},
handleTouchMove(e) {
if (!this.isDragging) return
const x = e.touches[0].clientX
this.offsetX += (x - this.startX)
this.startX = x
},
handleTouchEnd() {
this.isDragging = false
}
}
}
.custom-scroll {
display: flex;
transition: transform 0.3s ease;
}
.item {
flex-shrink: 0;
width: 200px;
}
使用 CSS scroll-snap 实现对齐效果
在滑动容器上添加 scroll-snap 属性,使滑动后自动对齐到最近的子元素。
.scroll-container {
scroll-snap-type: x mandatory;
overflow-x: auto;
display: flex;
}
.scroll-item {
scroll-snap-align: start;
flex-shrink: 0;
}
注意事项
- 移动端开发时需要考虑 touch 事件的兼容性
- 性能优化:大量子元素时建议使用虚拟滚动
- 滑动边界处理:限制最大最小偏移量
- 桌面端兼容:同时监听 mouse 事件







