Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

Dynamic Components

System transportu modułów w NOVA LAB pozwala podłączać różne panele do tego samego slotu stacji - panel tlenu, panel wody, panel energii. Vue ma mechanizm dynamic components - specjalny element

<component>
z atrybutem
:is
.

Podstawowa składnia

1<script setup>
2import { ref, shallowRef } from 'vue'
3import OxygenPanel from './OxygenPanel.vue'
4import WaterPanel from './WaterPanel.vue'
5import SolarPanel from './SolarPanel.vue'
6
7const tabs = { OxygenPanel, WaterPanel, SolarPanel }
8const currentTab = shallowRef(OxygenPanel)
9</script>
10
11<template>
12  <div class="station">
13    <nav>
14      <button
15        v-for="(comp, name) in tabs"
16        :key="name"
17        @click="currentTab = comp"
18      >
19        {{ name }}
20      </button>
21    </nav>
22
23    <component :is="currentTab" />
24  </div>
25</template>

Używamy

shallowRef
zamiast
ref
dla komponentów, bo nie potrzebujemy deep reactivity na obiekcie komponentu.

KeepAlive

Domyślnie przełączenie komponentu niszczy stary i tworzy nowy. Jeśli chcesz zachować stan (np. dane formularza), użyj

<KeepAlive>
:

1<template>
2  <KeepAlive>
3    <component :is="currentTab" />
4  </KeepAlive>
5</template>

Teraz komponent jest cachowany - wrócisz do niego z zachowanym stanem.

KeepAlive - include i exclude

Kontroluj które komponenty cachować:

1<template>
2  <!-- Tylko te komponenty -->
3  <KeepAlive :include="['OxygenPanel', 'WaterPanel']">
4    <component :is="currentTab" />
5  </KeepAlive>
6
7  <!-- Wszystkie oprócz tych -->
8  <KeepAlive :exclude="['HeavyModule']">
9    <component :is="currentTab" />
10  </KeepAlive>
11
12  <!-- Limit cache (LRU) -->
13  <KeepAlive :max="5">
14    <component :is="currentTab" />
15  </KeepAlive>
16</template>

Lifecycle hooks z KeepAlive

Cachowane komponenty mają dodatkowe hooki:

1<script setup>
2import { onActivated, onDeactivated } from 'vue'
3
4onActivated(() => {
5  console.log('Panel aktywowany (widoczny)')
6  // Odśwież dane, wznów timery
7})
8
9onDeactivated(() => {
10  console.log('Panel deaktywowany (ukryty)')
11  // Zatrzymaj timery, zapisz stan
12})
13</script>

Props na dynamicznych komponentach

Możesz przekazywać props do dynamicznych komponentów:

1<template>
2  <component
3    :is="currentTab"
4    :station="stationData"
5    @alert="handleAlert"
6  />
7</template>
Ir a CodeWorlds