vue实现抖动
Vue 实现抖动效果
在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动态控制样式。以下是几种常见的方法:
使用 CSS 动画
通过定义 @keyframes 实现抖动动画,再应用到 Vue 组件上。
.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); }
}
在 Vue 模板中动态绑定类名:
<template>
<div :class="{ shake: isShaking }" @click="triggerShake">点击抖动</div>
</template>
<script>
export default {
data() {
return {
isShaking: false
}
},
methods: {
triggerShake() {
this.isShaking = true
setTimeout(() => {
this.isShaking = false
}, 500)
}
}
}
</script>
使用 Vue Transition
结合 Vue 的 <transition> 组件和 CSS 动画实现。
<template>
<transition name="shake">
<div v-if="show" @click="shake">抖动元素</div>
</transition>
</template>
<style>
.shake-enter-active {
animation: shake 0.5s;
}
</style>
使用 JavaScript 动态样式
通过 Vue 的响应式数据动态修改样式属性。
<template>
<div
:style="shakeStyle"
@click="startShake"
>动态抖动</div>
</template>
<script>
export default {
data() {
return {
shakeStyle: {},
shakeCount: 0
}
},
methods: {
startShake() {
this.shakeCount = 0
this.doShake()
},
doShake() {
if (this.shakeCount >= 10) {
this.shakeStyle = { transform: 'translateX(0)' }
return
}
const direction = this.shakeCount % 2 === 0 ? -5 : 5
this.shakeStyle = { transform: `translateX(${direction}px)` }
this.shakeCount++
setTimeout(this.doShake, 50)
}
}
}
</script>
使用第三方库
可以集成如 animate.css 或 vue-kinesis 等库简化实现。
安装 animate.css:
npm install animate.css
在 Vue 中使用:

<template>
<div class="animated shake" v-if="isShaking">抖动效果</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isShaking: false
}
}
}
</script>
注意事项
- 抖动幅度和持续时间可通过调整 CSS 的
translateX值和animation-duration自定义。 - 频繁触发动画时建议清除旧动画,避免性能问题。
- 移动端需考虑硬件加速,可添加
will-change: transform优化性能。






