Kurs Vue.js · Moduł 13: Przejścia i animacje

TransitionGroup - animacja list

3 min czytania ·
W tej lekcji5

Lista modułów stacji NOVA LAB ciągle się zmienia - dodajemy nowe systemy podtrzymywania życia, usuwamy uszkodzone sensory, sortujemy alerty po priorytecie. Za każdym razem chcemy, aby zmiany w liście były wizualnie płynne. <TransitionGroup> to komponent Vue zaprojektowany specjalnie do animowania elementów renderowanych przez v-for.

Podstawowe użycie

<TransitionGroup name="list" tag="ul">
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>
</TransitionGroup>

Każdy element dodawany do listy animuje się przy wejściu, a usuwany - przy wyjściu. To automatyczne zachowanie bazujące na tych samych klasach CSS co <Transition>.

Kluczowe różnice od <Transition>

<TransitionGroup> różni się od <Transition> w kilku istotnych punktach:

  1. Renderuje element DOM - w przeciwieństwie do <Transition>, <TransitionGroup> domyślnie renderuje element HTML. Kontrolujesz go atrybutem tag: tag="ul", tag="div", tag="section". Jeśli nie chcesz dodatkowego elementu, możesz ustawić tag="template" (Vue 3.5+).

  2. Każdy element musi mieć unikalne :key - Vue musi śledzić tożsamość poszczególnych elementów, aby wiedzieć które dodać, usunąć i przesunąć. Nigdy nie używaj indeksu tablicy jako key!

  3. Obsługuje wiele elementów jednocześnie - nie jest ograniczony do jednego elementu jak <Transition>. Wiele elementów może wchodzić i wychodzić w tym samym czasie.

  4. Dodatkowa klasa -move - animuje przesuwanie elementów, gdy lista się zmienia kolejnością. To unikalna funkcja <TransitionGroup>.

  5. Tryb mode nie jest obsługiwany - ponieważ nie przełączamy między jednym elementem a drugim.

Klasy CSS dla listy

TransitionGroup używa tych samych klas co Transition plus dodatkowa klasa -move:

/* Wejście nowego elementu */
.list-enter-active {
  transition: all 0.5s ease;
}
.list-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

/* Wyjście usuwanego elementu */
.list-leave-active {
  transition: all 0.5s ease;
  position: absolute; /* WAŻNE! */
}
.list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* Przesuwanie pozostałych elementów */
.list-move {
  transition: transform 0.5s ease;
}

Move transitions - kluczowa mechanika

To najciekawsza funkcja <TransitionGroup>. Gdy dodajesz lub usuwasz element z listy, pozostałe elementy muszą się przesunąć na nowe pozycje. Vue automatycznie dodaje klasę -move do elementów, które zmieniają pozycję, i animuje ich ruch za pomocą transformacji CSS.

Aby move transitions działały poprawnie, elementy wychodzące muszą mieć position: absolute w klasie -leave-active. Dzięki temu wychodzący element "wychodzi z flow" i pozostałe mogą się płynnie przesunąć:

.list-leave-active {
  position: absolute;
  /* Opcjonalnie: zachowaj szerokość */
  width: 100%;
}

.list-move {
  transition: transform 0.5s ease;
}

Praktyczny przykład - lista alertów stacji

<template>
  <div class="alert-panel">
    <button @click="addAlert">Dodaj alert</button>

    <TransitionGroup name="alert" tag="div" class="alert-list">
      <div
        v-for="alert in alerts"
        :key="alert.id"
        class="alert-item"
        :class="alert.level"
      >
        {{ alert.message }}
        <button @click="removeAlert(alert.id)">x</button>
      </div>
    </TransitionGroup>
  </div>
</template>

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

const alerts = ref([])
let nextId = 1

function addAlert() {
  alerts.value.unshift({
    id: nextId++,
    message: `Alert #${nextId - 1}: Oxygen level check`,
    level: Math.random() > 0.5 ? 'warning' : 'critical'
  })
}

function removeAlert(id) {
  alerts.value = alerts.value.filter(a => a.id !== id)
}
</script>
.alert-enter-active, .alert-leave-active {
  transition: all 0.4s ease;
}
.alert-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}
.alert-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
.alert-leave-active {
  position: absolute;
}
.alert-move {
  transition: transform 0.4s ease;
}

Efekt: nowe alerty wchodzą z lewej, usuwane wychodzą w prawo, a pozostałe płynnie się przesuwają. Dokładnie jak na panelu alertów stacji kosmicznej!

Kod do tej lekcji: App.vue
<script setup>
import { ref } from 'vue'

const modules = ref([
  { id: 1, name: 'Generator tlenu', status: 'active' },
  { id: 2, name: 'Odzysk wody', status: 'active' },
  { id: 3, name: 'Panele słoneczne', status: 'active' }
])

let nextId = 4

function addModule() {
  const names = ['Osłona termiczna', 'Komputer nawigacyjny', 'Przekaźnik łączności', 'Szklarnia']
  const name = names[Math.floor(Math.random() * names.length)]
  modules.value.splice(
    Math.floor(Math.random() * (modules.value.length + 1)),
    0,
    { id: nextId++, name, status: 'active' }
  )
}

function removeModule(id) {
  const idx = modules.value.findIndex(m => m.id === id)
  if (idx > -1) modules.value.splice(idx, 1)
}

function shuffle() {
  modules.value = [...modules.value].sort(() => Math.random() - 0.5)
}
</script>

<template>
  <div class="nova-lab">
    <h1>Demo TransitionGroup</h1>

    <div class="controls">
      <button @click="addModule" class="btn add">+ Dodaj moduł</button>
      <button @click="shuffle" class="btn shuffle">Losuj</button>
    </div>

    <TransitionGroup name="list" tag="ul" class="module-list">
      <li v-for="mod in modules" :key="mod.id" class="module-item">
        <span>{{ mod.name }}</span>
        <button @click="removeModule(mod.id)" class="remove">×</button>
      </li>
    </TransitionGroup>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #00ff88;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; }
.controls { display: flex; gap: 10px; margin: 15px 0; }
.btn {
  border: none;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  color: white;
}
.add { background: #00b4d8; }
.shuffle { background: #9b59b6; }

.module-list {
  list-style: none;
  padding: 0;
}
.module-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(0, 180, 216, 0.1);
  border: 1px solid #00b4d8;
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: 8px;
}
.remove {
  background: #e74c3c;
  color: white;
  border: none;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
}

/* Klasy TransitionGroup */
.list-enter-active,
.list-leave-active {
  transition: all 0.4s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
/* Animacja przesunięcia */
.list-move {
  transition: transform 0.4s ease;
}
.list-leave-active {
  position: absolute;
}
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Czym <TransitionGroup> różni się od <Transition>?

  2. 2. Co robi atrybut tag='ul' w <TransitionGroup>?

To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    Użyj <TransitionGroup> z v-for i name='list' do animacji listy.

  • Klikanie w kolejności

    Ułóż poprawną składnię TransitionGroup:

  • Edytor kodu

    Użyj klasy .list-move z transition na transform do animacji przesunięcia.

  1. PytanieRóżnica Transition vs TransitionGroup
  2. PytanieAtrybut tag w TransitionGroup
  3. Zadanie z kodemPraktyka: TransitionGroup z listą
  4. PytanieWymagania TransitionGroup
  5. Kliknij w kolejnościSkładnia TransitionGroup
  6. Zadanie z kodemPraktyka: Move transitions

Przydatne artykuły