vue实现360度旋转
Vue 实现 360 度旋转
在 Vue 中实现 360 度旋转可以通过 CSS 动画或 JavaScript 动态控制样式。以下是两种常见方法:
使用 CSS 动画
通过 @keyframes 定义旋转动画,并将其应用到目标元素上。
<template>
<div class="rotating-element"></div>
</template>
<style>
.rotating-element {
width: 100px;
height: 100px;
background-color: #42b983;
animation: rotate 2s linear infinite;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
使用 Vue 动态绑定样式
通过 Vue 的响应式数据动态控制旋转角度,结合 setInterval 实现持续旋转。
<template>
<div
:style="{ transform: `rotate(${rotationDeg}deg)` }"
class="dynamic-rotate"
></div>
</template>
<script>
export default {
data() {
return {
rotationDeg: 0
};
},
mounted() {
setInterval(() => {
this.rotationDeg = (this.rotationDeg + 1) % 360;
}, 16); // 约60帧/秒
}
};
</script>
<style>
.dynamic-rotate {
width: 100px;
height: 100px;
background-color: #35495e;
transition: transform 0.1s linear;
}
</style>
使用第三方库(如 GSAP)
对于更复杂的动画效果,可以使用 GSAP 等动画库。
<template>
<div ref="rotateTarget" class="gsap-rotate"></div>
</template>
<script>
import { gsap } from 'gsap';
export default {
mounted() {
gsap.to(this.$refs.rotateTarget, {
rotation: 360,
duration: 2,
repeat: -1,
ease: 'linear'
});
}
};
</script>
<style>
.gsap-rotate {
width: 100px;
height: 100px;
background-color: #ff7e67;
}
</style>
注意事项
- 性能优化:CSS 动画通常性能更好,适合简单旋转。
- 交互控制:动态绑定样式更适合需要与用户交互控制的场景。
- 兼容性:确保
transform属性在目标浏览器中支持。







