vue实现抖动
Vue 实现抖动效果
抖动效果通常用于吸引用户注意力或提示操作反馈。以下是几种实现方式:
CSS Animation 实现
通过定义 @keyframes 实现抖动动画,适用于简单场景:

<template>
<div class="shake-element" @click="shake">点击抖动</div>
</template>
<style>
.shake-element {
display: inline-block;
padding: 10px 20px;
background: #42b983;
color: white;
cursor: pointer;
}
.shake {
animation: shake 0.5s;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
</style>
<script>
export default {
methods: {
shake() {
const el = document.querySelector('.shake-element')
el.classList.add('shake')
setTimeout(() => el.classList.remove('shake'), 500)
}
}
}
</script>
使用 Vue Transition
结合 Vue 的过渡系统实现可复用的抖动效果:

<template>
<button @click="isShaking = !isShaking">
<transition name="shake">
<span v-if="show">抖动内容</span>
</transition>
</button>
</template>
<style>
.shake-enter-active {
animation: shake 0.5s;
}
.shake-leave-active {
animation: shake 0.5s reverse;
}
/* 复用相同的 @keyframes */
</style>
第三方动画库
使用 animate.css 等成熟动画库快速实现:
npm install animate.css
<template>
<div
class="animated"
:class="{ 'shakeX': isShaking }"
@click="isShaking = true"
>
抖动元素
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return { isShaking: false }
},
watch: {
isShaking(val) {
if (val) setTimeout(() => this.isShaking = false, 1000)
}
}
}
</script>
GSAP 高级控制
需要精细控制动画时推荐使用 GSAP:
npm install gsap
<template>
<div ref="shakeTarget">高级抖动</div>
<button @click="startShake">开始</button>
</template>
<script>
import { gsap } from 'gsap'
export default {
methods: {
startShake() {
gsap.to(this.$refs.shakeTarget, {
x: -5, duration: 0.05, repeat: 5, yoyo: true
})
}
}
}
</script>
每种方案各有优势:CSS 方案最轻量,Transition 适合 Vue 生态,动画库方便快捷,GSAP 提供最专业的控制能力。根据项目复杂度选择合适方案即可。






