首页 / Vue3 入门教程 / 动画技巧

Vue3 入门教程

动画技巧

本教程共 40 篇 · 第 38 篇 · 更新于 2026-07-29 · 约 6 分钟阅读

VueVue3 入门教程动画Class动画状态驱动Watcher动画GSAP

38. 动画技巧

本节目标:学会用三种不依赖 <Transition> 的方式实现动画效果。

Class 动画

不是所有动画都涉及元素进出 DOM。有些动画是”状态变化时触发”——比如用户点击按钮后抖动提示。

思路:动态切换 CSS class 来触发动画。

<script setup>
import { ref } from 'vue'

const disabled = ref(false)

function warnDisabled() {
  disabled.value = true
  setTimeout(() => {
    disabled.value = false
  }, 1500)
}
</script>

<template>
  <div :class="{ shake: disabled }">
    <button @click="warnDisabled">点击我</button>
    <span v-if="disabled">该功能已禁用!</span>
  </div>
</template>
.shake {
  animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
  transform: translate3d(0, 0, 0);
}

@keyframes shake {
  10%, 90% { transform: translate3d(-1px, 0, 0); }
  20%, 80% { transform: translate3d(2px, 0, 0); }
  30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
  40%, 60% { transform: translate3d(4px, 0, 0); }
}
Tip

Class 动画适合一次性触发的效果。如果要循环触发,需要先移除 class 再添加。

状态驱动动画

有些动画是”跟某个值绑定”的——值变了,样式跟着变。比如鼠标位置决定背景色。

思路:用响应式数据绑定 style。

<script setup>
import { ref } from 'vue'

const x = ref(0)

function onMousemove(e) {
  x.value = e.clientX
}
</script>

<template>
  <div
    @mousemove="onMousemove"
    :style="{ backgroundColor: `hsl(${x}, 80%, 50%)` }"
    class="movearea"
  >
    <p>移动鼠标试试...</p>
    <p>x: {{ x }}</p>
  </div>
</template>
.movearea {
  transition: 0.3s background-color ease;
}

只要 CSS 里定义了 transition,响应式数据变化时浏览器会自动插值,形成平滑过渡。

除了颜色,也可以动画 transformwidthheight,甚至 SVG 路径的 d 属性。

Watcher 动画

有些动画需要”基于某个值,计算出另一个值”。比如数字滚动——用户输入目标值,数字从当前值平滑过渡过去。

思路:用 watch 监听变化,用动画库做过渡。

<script setup>
import { ref, reactive, watch } from 'vue'
import gsap from 'gsap'

const number = ref(0)
const tweened = reactive({ number: 0 })

watch(number, (n) => {
  gsap.to(tweened, { duration: 0.5, number: Number(n) || 0 })
})
</script>

<template>
  输入数字:<input v-model.number="number" />
  <p>{{ tweened.number.toFixed(0) }}</p>
</template>

工作流程:

  1. 用户在 input 里输入数字 → number 变化
  2. watch 捕获到变化 → 调用 GSAP
  3. GSAP 在 0.5 秒内把 tweened.number 从当前值过渡到目标值
  4. 模板里显示过渡中的值,形成滚动效果
Note

这种方式可以动画任何数值属性——位置、大小、颜色、透明度。只要你能用数字描述的状态,就能用 Watcher + 动画库来过渡。

三种技巧对比

技巧适合场景实现复杂度
Class 动画一次性触发(抖动、闪烁)
状态驱动动画跟用户交互实时联动
Watcher 动画数值过渡、复杂时间线

本节回顾

  • Class 动画:动态添加/移除 class 触发 CSS 动画
  • 状态驱动动画:响应式数据绑定 style,CSS transition 自动插值
  • Watcher 动画:watch 监听 + 动画库实现数值过渡
  • 这三种方式跟 <Transition> 互补,覆盖不同动画场景
  • 复杂动画推荐用 GSAP 等专业动画库