Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

reactive() - Reaktywne Systemy

Gdy pracujesz z kompleksowymi obiektami systemów,

reactive()
jest często wygodniejszy niż
ref()
- to jak kompletny panel kontrolny reaktora zamiast pojedynczych wskaźników.

Podstawy reactive()

1import { reactive } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  status: 'ACTIVE',
6  temperature: 2500,
7  readings: {
8    power: 850,
9    radiation: 12
10  }
11})
12
13// Dostęp bez .value!
14console.log(reactor.name) // 'Plasma Core Alpha'
15reactor.temperature = 2600
16
17// Zagnieżdżone obiekty też są reaktywne
18reactor.readings.power = 900 // To też wywoła aktualizację panelu

reactive() vs ref()

| Cecha | ref() | reactive() | |-------|-------|------------| | Dla prymitywów | Tak | Nie | | Dla obiektów | Tak (.value) | Tak (bezpośrednio) | | Destructuring | Bezpieczne | Traci reaktywność | | Reassign | Tak (.value = newObj) | Nie (tylko właściwości) |

Praktyczny Przykład

1<template>
2  <div class="reactor-panel" style="background: #0a0e27; color: #00ff88; border: 1px solid #00b4d8;">
3    <h2>{{ reactor.name }}</h2>
4    <p>Status: {{ reactor.status }}</p>
5    <p>Temperatura: {{ reactor.temperature }} K</p>
6    <p>Odczyty: {{ reactor.readings.power }} MW | {{ reactor.readings.radiation }} Sv/h</p>
7
8    <button @click="updateTemperature">Zwiększ temperaturę</button>
9  </div>
10</template>
11
12<script setup>
13import { reactive } from 'vue'
14
15const reactor = reactive({
16  name: 'Plasma Core Alpha',
17  status: 'ACTIVE',
18  temperature: 2500,
19  readings: {
20    power: 850,
21    radiation: 12
22  }
23})
24
25function updateTemperature() {
26  reactor.temperature += 100 // Bezpośrednia modyfikacja
27}
28</script>

Ograniczenia reactive()

1import { reactive } from 'vue'
2
3const reactor = reactive({ name: 'Plasma Core Alpha' })
4
5// ŹLE - zastąpienie całego obiektu
6reactor = { name: 'Plasma Core Beta' } // To nie zadziała!
7
8// DOBRZE - modyfikacja właściwości
9reactor.name = 'Plasma Core Beta'
10
11// ŹLE - destructuring traci reaktywność
12const { name } = reactor // name nie jest reaktywny!
13
14// DOBRZE - użyj toRefs
15import { toRefs } from 'vue'
16const { name } = toRefs(reactor) // name.value jest reaktywny
Ir a CodeWorlds