vue实现滑动
Vue 实现滑动效果的方法
使用 CSS 过渡和动画
通过 Vue 的过渡类名结合 CSS 实现滑动效果,适用于简单的元素滑动。

<template>
<div>
<button @click="show = !show">Toggle Slide</button>
<transition name="slide">
<div v-if="show" class="box">Slide Content</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
};
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter, .slide-leave-to {
transform: translateX(100%);
}
.box {
width: 200px;
height: 100px;
background: #42b983;
}
</style>
使用第三方库(如 Swiper.js)
对于复杂的滑动场景(如轮播图),可以使用 Swiper.js 等库。

<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
</div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/css/swiper.min.css';
export default {
mounted() {
new Swiper('.swiper-container', {
pagination: {
el: '.swiper-pagination',
},
});
}
};
</script>
自定义指令实现拖动滑动
通过 Vue 自定义指令实现元素的拖动滑动效果。
<template>
<div v-drag class="draggable" :style="{ left: position.x + 'px', top: position.y + 'px' }">
Drag Me
</div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 }
};
},
directives: {
drag: {
bind(el, binding, vnode) {
let startX, startY, initialX, initialY;
el.addEventListener('mousedown', startDrag);
function startDrag(e) {
startX = e.clientX;
startY = e.clientY;
initialX = vnode.context.position.x;
initialY = vnode.context.position.y;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', stopDrag);
}
function drag(e) {
vnode.context.position.x = initialX + e.clientX - startX;
vnode.context.position.y = initialY + e.clientY - startY;
}
function stopDrag() {
document.removeEventListener('mousemove', drag);
document.removeEventListener('mouseup', stopDrag);
}
}
}
}
};
</script>
<style>
.draggable {
width: 100px;
height: 100px;
background: #42b983;
position: absolute;
cursor: move;
}
</style>
使用 Touch 事件实现移动端滑动
针对移动端,可以通过 Touch 事件实现滑动交互。
<template>
<div
class="touch-area"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
:style="{ transform: `translateX(${offsetX}px)` }"
>
Slide Content
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
offsetX: 0
};
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
const currentX = e.touches[0].clientX;
this.offsetX = currentX - this.startX;
},
handleTouchEnd() {
this.offsetX = 0;
}
}
};
</script>
<style>
.touch-area {
width: 200px;
height: 100px;
background: #42b983;
touch-action: none;
}
</style>






