vue 实现滑动效果
Vue 实现滑动效果的常见方法
使用 CSS Transition 或 Animation
通过 Vue 的 v-bind:class 或 v-bind:style 动态绑定样式,结合 CSS 的 transition 或 animation 属性实现滑动效果。
<template>
<div
class="slider"
:style="{ transform: `translateX(${offset}px)` }"
></div>
</template>
<script>
export default {
data() {
return {
offset: 0
};
},
methods: {
slide() {
this.offset += 100; // 每次滑动 100px
}
}
};
</script>
<style>
.slider {
transition: transform 0.3s ease;
width: 100px;
height: 100px;
background: blue;
}
</style>
使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以方便地实现进入/离开的滑动动画。
<template>
<button @click="show = !show">Toggle Slide</button>
<transition name="slide">
<div v-if="show" class="box"></div>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
};
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s;
}
.slide-enter, .slide-leave-to {
transform: translateX(100%);
}
.box {
width: 100px;
height: 100px;
background: red;
}
</style>
使用第三方库(如 Swiper.js)
对于复杂的滑动场景(如轮播图),可以直接集成 Swiper 等专业库。
<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="item in 5" :key="item">
Slide {{ item }}
</div>
</div>
</div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/css/swiper.css';
export default {
mounted() {
new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 3000,
},
});
}
};
</script>
手势滑动(如 hammer.js)
通过手势库实现触摸滑动交互。
<template>
<div ref="panElement" class="pan-area"></div>
</template>
<script>
import Hammer from 'hammerjs';
export default {
mounted() {
const hammer = new Hammer(this.$refs.panElement);
hammer.on('pan', (event) => {
this.$refs.panElement.style.transform = `translateX(${event.deltaX}px)`;
});
}
};
</script>
<style>
.pan-area {
width: 200px;
height: 200px;
background: green;
touch-action: none;
}
</style>
关键注意事项
- 性能优化:对于频繁触发的滑动(如跟随鼠标),使用
requestAnimationFrame避免卡顿。 - 移动端适配:触摸事件需添加
touch-actionCSS 属性防止浏览器默认行为冲突。 - 动画流畅性:优先使用
transform和opacity属性,这些属性不会触发重排。







