vue实现左右滑动列表
Vue 实现左右滑动列表的方法
使用 CSS 和 touch 事件
通过 CSS 的 overflow-x 和 white-space 属性实现横向滚动,结合 Vue 的 @touchstart、@touchmove、@touchend 事件处理滑动逻辑。
<template>
<div
class="scroll-container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div class="scroll-content" :style="{ transform: `translateX(${offsetX}px)` }">
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 列表数据
startX: 0,
offsetX: 0,
isDragging: false
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.isDragging = true
},
handleTouchMove(e) {
if (!this.isDragging) return
const currentX = e.touches[0].clientX
this.offsetX += currentX - this.startX
this.startX = currentX
},
handleTouchEnd() {
this.isDragging = false
// 可以添加边界检测和惯性滑动逻辑
}
}
}
</script>
<style>
.scroll-container {
width: 100%;
overflow-x: hidden;
touch-action: pan-y;
}
.scroll-content {
display: flex;
white-space: nowrap;
transition: transform 0.3s ease;
}
.item {
flex: 0 0 auto;
width: 100px;
height: 100px;
margin-right: 10px;
background: #eee;
}
</style>
使用第三方库(如 vue-swipe)
安装 vue-swipe 库可以快速实现滑动列表功能。
npm install vue-swipe --save
<template>
<swipe class="my-swipe">
<swipe-item v-for="item in items" :key="item.id">
{{ item.text }}
</swipe-item>
</swipe>
</template>
<script>
import { Swipe, SwipeItem } from 'vue-swipe'
export default {
components: {
Swipe,
SwipeItem
},
data() {
return {
items: [...] // 列表数据
}
}
}
</script>
<style>
.my-swipe {
height: 100px;
}
</style>
使用 CSS Scroll Snap
CSS Scroll Snap 提供原生滚动对齐功能,适合实现分页滑动效果。
<template>
<div class="scroll-container">
<div class="scroll-content">
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</div>
</div>
</template>
<style>
.scroll-container {
width: 100%;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.scroll-content {
display: flex;
width: max-content;
}
.item {
scroll-snap-align: start;
width: 100vw;
height: 100px;
flex: 0 0 auto;
}
</style>
以上方法可根据项目需求选择,CSS 方案适合简单需求,第三方库提供更丰富的功能,CSS Scroll Snap 则利用浏览器原生特性实现流畅效果。







