vue实现icon转转
Vue 中实现图标旋转动画
在 Vue 中实现图标旋转效果可以通过 CSS 动画或 JavaScript 动态控制样式。以下是几种常见方法:
使用 CSS 动画
定义一个旋转的 CSS 动画关键帧,通过类名控制图标的旋转状态:
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.icon-rotate {
animation: spin 2s linear infinite;
}
在 Vue 组件中动态添加类名:
![]()
<template>
<div class="icon" :class="{ 'icon-rotate': isRotating }"></div>
<button @click="toggleRotate">切换旋转</button>
</template>
<script>
export default {
data() {
return {
isRotating: false
}
},
methods: {
toggleRotate() {
this.isRotating = !this.isRotating
}
}
}
</script>
使用 Vue 过渡效果
结合 Vue 的 transition 组件实现平滑旋转过渡:
<template>
<transition name="rotate">
<div class="icon" v-if="showRotated"></div>
</transition>
</template>
<style>
.rotate-enter-active, .rotate-leave-active {
transition: transform 0.5s;
}
.rotate-enter, .rotate-leave-to {
transform: rotate(180deg);
}
</style>
使用第三方动画库
安装 animate.css 库:
![]()
npm install animate.css
在组件中使用:
<template>
<div class="icon animate__animated animate__rotateIn"></div>
</template>
<script>
import 'animate.css'
export default {
// 组件逻辑
}
</script>
动态绑定样式
通过计算属性动态生成旋转样式:
<template>
<div
class="icon"
:style="{ transform: `rotate(${rotationDegrees}deg)` }"
></div>
<input type="range" v-model="rotationDegrees" min="0" max="360">
</template>
<script>
export default {
data() {
return {
rotationDegrees: 0
}
}
}
</script>
使用 SVG 图标旋转
如果使用 SVG 图标,可以直接操作 SVG 元素的 transform 属性:
<template>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
:style="{ transform: `rotate(${angle}deg)` }"
>
<path d="M12 2L4 12l8 10 8-10z"/>
</svg>
</template>
选择哪种方法取决于具体需求,CSS 动画适合简单的无限旋转,Vue 过渡适合状态变化的旋转,而动态绑定样式则提供更精确的控制。






