vue实现旋转效果
使用 CSS transform 实现旋转
在 Vue 中实现旋转效果可以通过 CSS 的 transform 属性结合 transition 实现平滑动画。在模板中绑定样式,通过数据控制旋转状态。
<template>
<div
class="rotate-box"
:style="{ transform: `rotate(${rotateDeg}deg)` }"
@click="toggleRotate"
>
点击旋转
</div>
</template>
<script>
export default {
data() {
return {
rotateDeg: 0,
isRotated: false
}
},
methods: {
toggleRotate() {
this.isRotated = !this.isRotated
this.rotateDeg = this.isRotated ? 180 : 0
}
}
}
</script>
<style>
.rotate-box {
width: 100px;
height: 100px;
background-color: #42b983;
display: flex;
align-items: center;
justify-content: center;
transition: transform 0.5s ease;
cursor: pointer;
}
</style>
使用 Vue Transition 组件
对于更复杂的旋转动画,可以使用 Vue 内置的 <transition> 组件,结合 CSS 动画类名控制旋转过程。
<template>
<button @click="show = !show">切换旋转</button>
<transition name="rotate">
<div v-if="show" class="rotating-item"></div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
<style>
.rotating-item {
width: 100px;
height: 100px;
background-color: #ff7043;
margin-top: 20px;
}
.rotate-enter-active, .rotate-leave-active {
transition: all 0.5s;
}
.rotate-enter, .rotate-leave-to {
transform: rotate(180deg);
opacity: 0;
}
</style>
使用第三方动画库
对于更丰富的旋转效果,可以引入第三方动画库如 animate.css 或 GSAP:
<template>
<div
class="animated"
:class="{ 'rotateIn': isRotating }"
@click="isRotating = !isRotating"
>
点击旋转
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isRotating: false
}
}
}
</script>
<style>
div {
width: 100px;
height: 100px;
background-color: #2196F3;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
</style>
使用 JavaScript 动画库 (GSAP)
对于需要精细控制的旋转动画,GSAP 提供更强大的功能:
<template>
<div ref="box" class="gsap-box" @click="rotateBox">
点击旋转
</div>
</template>
<script>
import { gsap } from 'gsap'
export default {
methods: {
rotateBox() {
gsap.to(this.$refs.box, {
rotation: 360,
duration: 1,
ease: "elastic.out(1, 0.3)"
})
}
}
}
</script>
<style>
.gsap-box {
width: 100px;
height: 100px;
background-color: #9c27b0;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
</style>
无限旋转动画
实现元素持续旋转的效果,可以通过 CSS 动画关键帧实现:

<template>
<div class="infinite-rotate"></div>
</template>
<style>
.infinite-rotate {
width: 100px;
height: 100px;
background-color: #ff9800;
animation: spin 2s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>






