You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+Vite项目中JSX组件如何编写CSS @keyframes动画

在Vue3 JSX中用@styils/vue实现Loading组件的旋转动画

原.vue组件参考

原组件核心动画实现:

<template>
  <div class="loading-spinner"></div>
</template>

<style scoped>
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
</style>

JSX + @styils/vue实现方案

@styils/vue提供keyframes函数定义CSS动画,配合css或styled函数即可在JSX中复现原动画效果:

方案1:使用css函数绑定样式

import { defineComponent } from 'vue'
import { css, keyframes } from '@styils/vue'

// 定义旋转动画
const spinAnimation = keyframes({
  from: { transform: 'rotate(0deg)' },
  to: { transform: 'rotate(360deg)' }
})

export default defineComponent({
  setup() {
    // 生成Spinner的样式类名
    const spinnerClass = css({
      width: '40px',
      height: '40px',
      border: '4px solid #f3f3f3',
      borderTop: '4px solid #3498db',
      borderRadius: '50%',
      // 引用定义好的动画
      animation: `${spinAnimation} 1s linear infinite`
    })

    return () => <div class={spinnerClass}></div>
  }
})

方案2:使用styled组件(更简洁)

import { defineComponent } from 'vue'
import { styled, keyframes } from '@styils/vue'

// 定义旋转动画
const spinAnimation = keyframes({
  from: { transform: 'rotate(0deg)' },
  to: { transform: 'rotate(360deg)' }
})

// 创建预样式化的Spinner组件
const LoadingSpinner = styled.div({
  width: '40px',
  height: '40px',
  border: '4px solid #f3f3f3',
  borderTop: '4px solid #3498db',
  borderRadius: '50%',
  animation: `${spinAnimation} 1s linear infinite`
})

export default defineComponent({
  setup() {
    return () => <LoadingSpinner />
  }
})

关键说明

  • keyframes函数接收动画关键帧对象,键支持from/to或百分比(如'50%'),值为对应样式对象。
  • 在样式中通过模板字符串${spinAnimation}引用动画,和原生CSS的animation属性用法一致。
  • @styils/vue会自动处理样式作用域和动画注入,无需手动管理全局样式冲突。

内容的提问来源于stack exchange,提问作者Brant Ge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:37:30