vue实现抖动样式
实现抖动效果的CSS方法
在Vue中实现抖动效果可以通过CSS动画或第三方库完成。以下是几种常见方法:
CSS关键帧动画
定义一个@keyframes抖动动画并应用到元素:
.shake {
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}
@keyframes shake {
10%, 90% { transform: translate3d(-1px, 0, 0); }
20%, 80% { transform: translate3d(2px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
40%, 60% { transform: translate3d(4px, 0, 0); }
}
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>
使用第三方动画库
安装animate.css库:
npm install animate.css
在Vue组件中使用:

<template>
<div class="animate__animated" :class="{'animate__headShake': isShaking}">
头部抖动效果
</div>
</template>
<script>
import 'animate.css'
export default {
data() { return { isShaking: false } }
}
</script>
自定义指令实现
创建全局抖动指令:
// main.js
Vue.directive('shake', {
inserted(el, binding) {
el.addEventListener('click', () => {
el.classList.add('shake')
setTimeout(() => el.classList.remove('shake'), 500)
})
}
})
使用指令:
<div v-shake>点击触发指令抖动</div>
性能优化建议
对于频繁触发的抖动动画,建议使用will-change属性优化:
.shake {
will-change: transform;
/* 其他动画属性 */
}
以上方法可根据实际需求选择,CSS动画方案性能最佳,第三方库提供更多预设效果,自定义指令则更适合全局复用场景。






