vue实现卡片左右滑动
实现卡片左右滑动的方法
使用Vue实现卡片左右滑动可以通过多种方式,以下是几种常见的方法:

使用CSS和Touch事件
通过监听touchstart、touchmove和touchend事件,结合CSS的transform属性实现滑动效果。

<template>
<div
class="card-container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${offsetX}px)` }"
>
<div v-for="(card, index) in cards" :key="index" class="card">
{{ card.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
cards: [
{ content: 'Card 1' },
{ content: 'Card 2' },
{ content: 'Card 3' }
],
startX: 0,
offsetX: 0,
currentX: 0
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX
this.currentX = this.offsetX
},
handleTouchMove(e) {
const x = e.touches[0].clientX
this.offsetX = this.currentX + x - this.startX
},
handleTouchEnd() {
// 添加滑动结束后的逻辑,如自动对齐到最近的卡片
}
}
}
</script>
<style>
.card-container {
display: flex;
transition: transform 0.3s ease;
width: 100%;
}
.card {
flex: 0 0 80%;
margin: 0 10px;
height: 200px;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用第三方库(如Swiper.js)
Swiper.js是一个流行的滑动组件库,支持Vue集成,提供丰富的滑动效果和配置选项。
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(card, index) in cards" :key="index">
<div class="card">
{{ card.content }}
</div>
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
cards: [
{ content: 'Card 1' },
{ content: 'Card 2' },
{ content: 'Card 3' }
],
swiperOptions: {
slidesPerView: 'auto',
spaceBetween: 20,
freeMode: true
}
}
}
}
</script>
<style>
.card {
height: 200px;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用CSS Scroll Snap
CSS Scroll Snap是一种纯CSS实现滑动效果的方法,适合简单的滑动需求。
<template>
<div class="scroll-container">
<div v-for="(card, index) in cards" :key="index" class="card">
{{ card.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
cards: [
{ content: 'Card 1' },
{ content: 'Card 2' },
{ content: 'Card 3' }
]
}
}
}
</script>
<style>
.scroll-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
width: 100%;
}
.card {
flex: 0 0 80%;
margin: 0 10px;
height: 200px;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
scroll-snap-align: start;
}
</style>
选择合适的方法
- 如果需要高度自定义的滑动效果,可以选择第一种方法。
- 如果需要快速实现丰富的滑动功能,推荐使用Swiper.js。
- 如果项目对性能要求较高且功能简单,CSS Scroll Snap是不错的选择。






