vue实现icon转转
Vue 实现图标旋转动画
在 Vue 中实现图标旋转效果可以通过 CSS 动画或 JavaScript 动画库完成。以下是几种常见方法:
使用 CSS animation 属性
通过定义 CSS 关键帧动画并绑定到图标元素上:
<template>
<div class="rotating-icon">
<i class="icon" :class="iconClass"></i>
</div>
</template>
<style>
.icon {
display: inline-block;
}
.rotate {
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<script>
export default {
props: {
iconClass: {
type: String,
default: 'fas fa-spinner' // Font Awesome 示例
}
}
}
</script>
使用 Vue 过渡效果
结合 Vue 的过渡系统实现条件触发的旋转:
<template>
<transition name="rotate">
<i class="fas fa-sync-alt" v-if="isRotating"></i>
</transition>
</template>
<style>
.rotate-enter-active {
animation: spin 1s;
}
.rotate-leave-active {
animation: spin 1s reverse;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
使用 GSAP 动画库
对于更复杂的旋转动画,可以使用 GSAP 实现精准控制:
<template>
<i ref="icon" class="fas fa-cog"></i>
<button @click="rotate">开始旋转</button>
</template>
<script>
import gsap from 'gsap'
export default {
methods: {
rotate() {
gsap.to(this.$refs.icon, {
rotation: 360,
duration: 2,
repeat: -1,
ease: "none"
})
}
}
}
</script>
动态控制旋转状态
通过响应式数据控制旋转状态:
<template>
<i
class="fas fa-refresh"
:style="{ transform: `rotate(${rotationDegrees}deg)` }"
@click="startRotation"
></i>
</template>
<script>
export default {
data() {
return {
rotationDegrees: 0,
rotationInterval: null
}
},
methods: {
startRotation() {
this.rotationInterval = setInterval(() => {
this.rotationDegrees = (this.rotationDegrees + 2) % 360
}, 16)
},
stopRotation() {
clearInterval(this.rotationInterval)
}
},
beforeDestroy() {
this.stopRotation()
}
}
</script>
使用第三方组件库
若使用组件库如 Element UI:
<template>
<el-icon class="is-loading">
<Refresh />
</el-icon>
</template>
<script>
import { Refresh } from '@element-plus/icons-vue'
export default {
components: { Refresh }
}
</script>
每种方法适用于不同场景,CSS 动画适合简单无限旋转,GSAP 适合复杂动画序列,响应式控制适合需要精确交互的场景。
![]()






