Skip to content
On this page

动画技巧

Vue 提供了 <Transition><TransitionGroup> 组件来处理进入、离开或是列表的过渡。但是在网页上制作动画的方式非常多,即使是在一个 Vue 应用中。这里我们会探讨一些别的技巧。

基于 CSS 类的动画

对于那些不是正在进入或离开 DOM 的元素,我们可以通过给它们动态添加 CSS 类来触发动画:

const notActivated = ref(false)
function warnNotActivated() {
  notActivated.value = true
  setTimeout(() => {
    notActivated.value = false
  }, 1500)
}
export default {
  data() {
    return {
      notActivated: false
    }
  },
  methods: {
    warnNotActivated() {
      this.notActivated = true
      setTimeout(() => {
        this.notActivated = false
      }, 1500)
    }
  }
}
<div :class="{ shake: notActivated }">
  <button @click="warnNotActivated">点击此处</button>
  <span v-if="notActivated">此功能未激活。</span>
</div>
.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);
  }
}

状态驱动的动画

某些过渡效果可以通过插值来应用,例如,通过在交互发生时将样式绑定到元素。看看下面这个示例:

const x = ref(0)
function onMousemove(e) {
  x.value = e.clientX
}
export default {
  data() {
    return {
      x: 0
    }
  },
  methods: {
    onMousemove(e) {
      this.x = e.clientX
    }
  }
}
<div
  @mousemove="onMousemove"
  :style="{ backgroundColor: `hsl(${x}, 80%, 50%)` }"
  class="movearea"
>
  <p>移动鼠标穿过这个 div...</p>
  <p>x: {{ x }}</p>
</div>
.movearea {
  transition: 0.3s background-color ease;
}

Move your mouse across this div...

x: 0

除了颜色外,你还可以使用样式绑定动画转换、宽度或高度。你甚至可以通过运用弹簧物理学为 SVG 添加动画,毕竟它们也只是 attribute 的数据绑定:

带侦听器的动画

在一些动画创意里,我们可以根据一些数字状态,使用侦听器将任何东西做成动画。例如,我们可以将数字本身变成动画:

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 })
})
import gsap from 'gsap'
export default {
  data() {
    return {
      number: 0,
      tweened: 0
    }
  },
  watch: {
    number(n) {
      gsap.to(this, { duration: 0.5, tweened: Number(n) || 0 })
    }
  }
}
输入一个数字:<input v-model.number="number" />
<p>{{ tweened.number.toFixed(0) }}</p>
输入一个数字:

0

动画技巧 has loaded