Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

Głęboka vs Płytka Reaktywność

Vue oferuje różne poziomy reaktywności - jak różne warstwy sensorów w reaktorze.

Deep Reactivity (domyślnie)

1import { ref, reactive } from 'vue'
2
3// ref z obiektem - głęboka reaktywność
4const missionControl = ref({
5  station: 'NOVA LAB',
6  modules: [
7    { id: 1, name: 'Oxygen Generator' },
8    { id: 2, name: 'Water Recycler' }
9  ]
10})
11
12// Zmiany na każdym poziomie są reaktywne
13missionControl.value.station = 'NOVA LAB Alpha'
14missionControl.value.modules[0].name = 'Oxygen Generator Prime'
15missionControl.value.modules.push({ id: 3, name: 'Power Core' })
16// Wszystkie powyższe wywołają aktualizację panelu kontrolnego

shallowRef() - Płytka Reaktywność

1import { shallowRef } from 'vue'
2
3const missionControl = shallowRef({
4  station: 'NOVA LAB',
5  modules: [{ id: 1, name: 'Oxygen Generator' }]
6})
7
8// Tylko zamiana .value jest reaktywna
9missionControl.value.station = 'Nowa nazwa' // NIE wywoła aktualizacji!
10missionControl.value.modules.push({...}) // NIE wywoła aktualizacji!
11
12// TO zadziała - zamiana całego obiektu
13missionControl.value = {
14  station: 'NOVA LAB Beta',
15  modules: []
16}

shallowReactive()

1import { shallowReactive } from 'vue'
2
3const missionControl = shallowReactive({
4  station: 'NOVA LAB',
5  location: {
6    planet: 'Mars',
7    year: 2087
8  }
9})
10
11missionControl.station = 'Nowa stacja' // Reaktywne - poziom 1
12missionControl.location.planet = 'Europa' // NIE reaktywne - poziom 2
13
14// Musisz zastąpić cały obiekt location
15missionControl.location = { planet: 'Europa', year: 2087 }

Kiedy używać shallow?

| Sytuacja | Użyj | |----------|------| | Duże obiekty z API | shallowRef | | Biblioteki zewnętrzne | shallowRef | | Optymalizacja wydajności | shallow* | | Typowe dane UI | ref/reactive |

Praktyczny Przykład

1<template>
2  <div class="sensor-display" style="background: #0a0e27; color: #00ff88;">
3    <h2>{{ sensorData.systemName }}</h2>
4    <button @click="refreshData">Odśwież odczyty</button>
5  </div>
6</template>
7
8<script setup>
9import { shallowRef } from 'vue'
10
11// Duże dane z sensorów - płytka reaktywność
12const sensorData = shallowRef({
13  systemName: 'Reactor Monitoring',
14  readings: [] // Tysiące odczytów z sensorów
15})
16
17async function refreshData() {
18  const response = await fetch('/api/sensors')
19  // Zamiana całego obiektu - reaktywne
20  sensorData.value = await response.json()
21}
22</script>
Ir a CodeWorlds