vue实现旋转效果
Vue 实现旋转效果的方法
使用 CSS 动画
通过 Vue 绑定 CSS 类或内联样式,利用 CSS 的 transform 和 animation 属性实现旋转效果。
<template>
<div :class="{ 'rotate': isRotating }" @click="toggleRotate">
点击旋转
</div>
</template>
<script>
export default {
data() {
return {
isRotating: false
};
},
methods: {
toggleRotate() {
this.isRotating = !this.isRotating;
}
}
};
</script>
<style>
.rotate {
animation: rotate 2s linear infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
使用 Vue 过渡效果
结合 Vue 的 <transition> 组件和 CSS 过渡实现平滑旋转。
<template>
<button @click="show = !show">切换旋转</button>
<transition name="rotate">
<div v-if="show" class="box"></div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
};
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
}
.rotate-enter-active {
animation: rotate-in 0.5s;
}
.rotate-leave-active {
animation: rotate-out 0.5s;
}
@keyframes rotate-in {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes rotate-out {
from { transform: rotate(360deg); }
to { transform: rotate(0deg); }
}
</style>
使用 JavaScript 动态控制
通过 Vue 的响应式数据和 requestAnimationFrame 实现更灵活的旋转控制。
<template>
<div
:style="{ transform: `rotate(${angle}deg)` }"
class="box"
@click="startRotate"
>
点击旋转
</div>
</template>
<script>
export default {
data() {
return {
angle: 0,
rotating: false
};
},
methods: {
startRotate() {
this.rotating = !this.rotating;
if (this.rotating) {
this.animateRotate();
}
},
animateRotate() {
if (!this.rotating) return;
this.angle = (this.angle + 2) % 360;
requestAnimationFrame(this.animateRotate);
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
transition: transform 0.1s linear;
}
</style>
使用第三方库(如 GSAP)
通过 Vue 结合 GSAP 实现高级旋转动画效果。

<template>
<div ref="rotateElement" class="box" @click="rotateWithGSAP">
点击旋转(GSAP)
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
methods: {
rotateWithGSAP() {
gsap.to(this.$refs.rotateElement, {
rotation: 360,
duration: 1,
repeat: -1,
ease: "power1.inOut"
});
}
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #42b983;
}
</style>
注意事项
- CSS 动画性能通常优于 JavaScript 动画,适合简单效果。
- 动态控制旋转角度时,注意性能优化,避免频繁触发重排。
- GSAP 等库提供更丰富的动画功能,但会增加项目体积。






