Vue 提供的 <transition> 元件,能讓元素進出畫面時自動套用動畫效果,不用額外的 JS,只須加上 class 名稱就能做到
<template>
  <button @click="show = !show">切換</button>
  <transition name="fade">
    <p v-if="show" class="box">Hello Vue!</p>
  </transition>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(true)
</script>
<style scoped>
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.fade-enter-to, .fade-leave-from {
  opacity: 1;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.box {
  background: #f4f4f4;
  padding: 1rem;
  border-radius: 8px;
}
</style>
對多個元素同時套用動畫,範例如下:
<template>
  <button @click="addItem">新增項目</button>
  <transition-group name="list" tag="ul">
    <li v-for="item in items" :key="item" class="list-item">
      {{ item }}
    </li>
  </transition-group>
</template>
<script setup>
import { ref } from 'vue'
const items = ref(['台大資管', '政大資管'])
function addItem() {
  items.value.push('清大資工')
}
</script>
<style scoped>
.list-item {
  margin: 4px 0;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 6px;
}
.list-enter-active, .list-leave-active {
  transition: all 0.4s ease;
}
.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
小結
- transition 動畫使用
- transition-group 群組動畫使用