vue实现抖动样式
Vue 实现抖动样式的方法
在 Vue 中实现抖动效果可以通过 CSS 动画或第三方库来实现。以下是几种常见的实现方式:
使用 CSS 动画
定义一个抖动的关键帧动画,并在 Vue 组件中应用:
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
.shake {
animation: shake 0.5s ease-in-out;
}
在 Vue 模板中动态添加类名:

<template>
<button @click="shake" :class="{ shake: isShaking }">点击抖动</button>
</template>
<script>
export default {
data() {
return {
isShaking: false
}
},
methods: {
shake() {
this.isShaking = true
setTimeout(() => {
this.isShaking = false
}, 500)
}
}
}
</script>
使用 Vue Transition
Vue 的 <transition> 组件也可以实现抖动效果:
<template>
<button @click="shake">点击抖动</button>
<transition name="shake">
<div v-if="show" class="shake-box">抖动元素</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
shake() {
this.show = true
setTimeout(() => {
this.show = false
}, 500)
}
}
}
</script>
<style>
.shake-enter-active {
animation: shake 0.5s;
}
.shake-leave-active {
animation: shake 0.5s reverse;
}
@keyframes shake {
/* 同上 */
}
</style>
使用第三方库
安装 vue-shake 或其他动画库:

npm install vue-shake
在组件中使用:
<template>
<shake>
<button>抖动按钮</button>
</shake>
</template>
<script>
import { Shake } from 'vue-shake'
export default {
components: {
Shake
}
}
</script>
自定义指令实现
创建一个自定义抖动指令:
Vue.directive('shake', {
inserted(el) {
el.addEventListener('click', () => {
el.classList.add('shake')
setTimeout(() => {
el.classList.remove('shake')
}, 500)
})
}
})
使用指令:
<button v-shake>点击抖动</button>
以上方法都可以在 Vue 中实现抖动效果,选择适合项目需求的方式即可。CSS 动画方式性能较好且不依赖第三方库,适合简单需求;第三方库则提供更多预设效果和配置选项。






