vue实现滑动效果
使用CSS过渡实现滑动效果
在Vue中可以通过CSS的transition属性配合Vue的v-if或v-show指令实现基础滑动效果。定义一个包含transition的CSS类,并在元素上应用这个类。

<template>
<div>
<button @click="show = !show">Toggle Slide</button>
<transition name="slide">
<div v-if="show" class="box">滑动内容</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: all 0.5s ease;
}
.slide-enter, .slide-leave-to {
transform: translateX(100px);
opacity: 0;
}
.box {
width: 200px;
height: 100px;
background: #42b983;
}
</style>
使用第三方动画库
Vue可以结合第三方动画库如animate.css实现更丰富的滑动效果。安装后直接在transition组件中指定动画类名即可。

npm install animate.css
<template>
<transition
enter-active-class="animate__animated animate__slideInLeft"
leave-active-class="animate__animated animate__slideOutRight"
>
<div v-if="show" class="box">滑动内容</div>
</transition>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
show: false
}
}
}
</script>
使用JavaScript钩子实现复杂动画
对于需要精细控制的滑动效果,可以使用Vue的JavaScript过渡钩子函数。这些钩子包括beforeEnter、enter、afterEnter等,允许用JavaScript直接操作DOM。
<template>
<div>
<button @click="show = !show">Toggle</button>
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
beforeEnter(el) {
el.style.opacity = 0
el.style.transform = 'translateX(100px)'
},
enter(el, done) {
const animation = el.animate([
{ transform: 'translateX(100px)', opacity: 0 },
{ transform: 'translateX(0)', opacity: 1 }
], {
duration: 500
})
animation.onfinish = done
},
leave(el, done) {
const animation = el.animate([
{ transform: 'translateX(0)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0 }
], {
duration: 500
})
animation.onfinish = done
}
}
}
</script>
列表滑动过渡
对于列表项,可以使用transition-group组件实现多个元素的滑动过渡效果。需要为每个元素设置唯一的key属性。
<template>
<div>
<button @click="addItem">Add Item</button>
<button @click="removeItem">Remove Item</button>
<transition-group name="list" tag="ul">
<li v-for="item in items" :key="item" class="list-item">
{{ item }}
</li>
</transition-group>
</div>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3, 4, 5],
nextNum: 6
}
},
methods: {
addItem() {
this.items.splice(Math.floor(Math.random() * this.items.length), 0, this.nextNum++)
},
removeItem() {
this.items.splice(Math.floor(Math.random() * this.items.length), 1)
}
}
}
</script>
<style>
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
</style>






