Kurs Vue.js · Moduł 3: Reaktywność

toRef i toRefs - Bezpieczne Rozpakowywanie Sensorów

4 min czytania ·
W tej lekcji6

Czasem potrzebujesz wyciągnąć pojedyncze właściwości z reaktywnego obiektu sensora, zachowując reaktywność - jak wydzielenie konkretnych odczytów z kompleksowego systemu monitoringu.

Chcesz przekazać samą temperaturę do funkcji wyświetlacza albo nadać polom krótsze nazwy w szablonie, więc sięgasz po destrukturyzację. Wygląda niewinnie, ale z obiektu reaktywnego wyjmuje tylko zdjęcie odczytu z jednej chwili. Ta lekcja pokazuje, jak wyjąć właściwość razem z przewodem, który dalej przewodzi zmiany.

Problem z Destructuring

Zobacz, co się dzieje z wartościami wyjętymi z obiektu reactive(), gdy obiekt później się zmieni:

import { reactive } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha',
  temperature: 2500
})

// ŹLE - traci reaktywność!
const { name, temperature } = reactor
console.log(name) // 'Plasma Core Alpha' - ale nie jest reaktywny

reactor.name = 'Plasma Core Beta'
console.log(name) // Nadal 'Plasma Core Alpha'!

Zmienna name dostała zwykły napis skopiowany w chwili destrukturyzacji. Obiekt reactor zmienił się poprawnie, ale kopia o tym nie wie i nie odświeży żadnego widoku. To samo stanie się, gdy przekażesz reactor.temperature do funkcji: dostanie ona liczbę, a nie połączenie z reaktorem.

toRef() - Pojedynczy Sensor

toRef(obiekt, 'klucz') tworzy ref powiązany z jedną właściwością. Połączenie działa w obie strony:

import { reactive, toRef } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha',
  temperature: 2500
})

// toRef tworzy reaktywną referencję do odczytu
const nameRef = toRef(reactor, 'name')

console.log(nameRef.value) // 'Plasma Core Alpha'

reactor.name = 'Plasma Core Beta'
console.log(nameRef.value) // 'Plasma Core Beta' - zsynchronizowane!

nameRef.value = 'Plasma Core Gamma'
console.log(reactor.name) // 'Plasma Core Gamma' - dwukierunkowe!

nameRef nie przechowuje własnej kopii, tylko czyta i zapisuje reactor.name. To inna sytuacja niż ref(reactor.name), które dostałoby zwykły napis i nie byłoby z niczym zsynchronizowane.

toRefs() - Wszystkie Sensory

toRefs() robi to samo naraz dla wszystkich właściwości i zwraca zwykły obiekt pełen refów, który można bezpiecznie zdestrukturyzować:

import { reactive, toRefs } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha',
  temperature: 2500,
  status: 'ACTIVE'
})

// toRefs konwertuje wszystkie właściwości
const { name, temperature, status } = toRefs(reactor)

// Każda jest teraz ref z .value
console.log(name.value) // 'Plasma Core Alpha'
console.log(temperature.value)  // 2500

// Zmiany są zsynchronizowane
reactor.temperature = 2600
console.log(temperature.value) // 2600

toRefs tworzy refy tylko dla właściwości, które istnieją w chwili wywołania. Pole dodane później nie dostanie refa - dla pola opcjonalnego użyj toRef. Ten sam mechanizm przydaje się, gdy funkcja zwraca stan: zwrócenie toRefs(state) pozwala odbiorcy zdestrukturyzować wynik bez utraty reaktywności.

Użycie w Komponentach

W archiwum stacji przechowujemy holograficzne kopie ziemskich dzieł sztuki. Formularz edycji używa v-model, dyrektywy wiązania dwukierunkowego: wpisany tekst trafia do danych, a zmiana danych wraca do pola. Szczegółowo poznasz ją w module 5.

<template>
  <div>
    <input v-model="title" />
    <p>Rok: {{ year }}</p>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'

const artwork = reactive({
  title: 'Mona Lisa',
  year: 1503
})

// Rozpakuj do użycia w template
const { title, year } = toRefs(artwork)
</script>

Wpisywanie w pole zmienia artwork.title przez ref title. W szablonie mógłbyś równie dobrze pisać artwork.title - toRefs najbardziej przydaje się wtedy, gdy zwracasz stan z funkcji albo przekazujesz go dalej.

toRef z Domyślną Wartością

Trzeci argument toRef to wartość domyślna, używana wtedy, gdy właściwość ma wartość undefined:

import { reactive, toRef } from 'vue'

const reactor = reactive({
  name: 'Plasma Core Alpha'
  // brak 'maxTemperature'
})

// Z wartością domyślną (Vue 3.2.25+)
const maxTemperature = toRef(reactor, 'maxTemperature', 5000)
console.log(maxTemperature.value) // 5000

Obiekt reactor nie zyskał przy tym nowego pola - wartość domyślna żyje tylko w refie. Przydaje się przy paczkach telemetrii, w których część pól bywa pusta.

Praktyczny Przykład - Props

Props to dane, które komponent dostaje od rodzica. Makro defineProps deklaruje je bez importu, a zapis typu w nawiasach ostrych wymaga lang="ts":

<!-- SensorDisplay.vue -->
<script setup lang="ts">
import { toRefs } from 'vue'

const props = defineProps<{
  sensorName: string
  reading: number
}>()

// Rozpakuj props z zachowaniem reaktywności
const { sensorName, reading } = toRefs(props)

// Teraz możesz użyć w watch, computed itp.
</script>

Obiekt props jest reaktywny, więc toRefs daje refy, które nadążają za rodzicem. Od Vue 3.5 nawet zmienne zdestrukturyzowane wprost z defineProps() pozostają reaktywne, bo kompilator zamienia je na props.sensorName. Gdy jednak przekazujesz taki props do innej funkcji, nadal potrzebujesz refa albo gettera () => props.reading. Komponenty i props poznasz w module 6.

Mój wybór: toRef dla jednego pola, toRefs dla całego obiektu, a w prostym szablonie zwykły zapis z kropką. W następnej lekcji poznasz narzędzia, które powiedzą Ci, czy dana wartość jest refem, obiektem reaktywnym, czy zwykłą kopią.

Zapamiętaj: destrukturyzacja robi zdjęcie odczytu, a toRef i toRefs podłączają przewód, który przewodzi zmiany w obie strony.

Kod do tej lekcji: App.vue
<script setup>
import { ref, reactive, isRef, isReactive, unref } from 'vue'

// Diagnostyka systemów - isRef(), isReactive(), unref()
// Sprawdzanie typów reaktywności w NOVA LAB

// Różne typy danych
const systemName = ref('Plasma Core System')
const isPowered = ref(true)
const powerLevel = ref(75)

const systemConfig = reactive({
  id: 'SYS-001',
  type: 'REACTOR',
  online: true,
  sensors: {
    temperature: 850,
    pressure: 120
  }
})

const normalString = 'This is not reactive'
const normalNumber = 42
const normalObject = { test: 'value' }

// Funkcja diagnostyczna
function diagnoseValue(value, name) {
  return {
    name,
    isRef: isRef(value),
    isReactive: isReactive(value),
    rawValue: unref(value), // unref() zwraca wartość bez .value
    type: typeof value
  }
}

// Wyniki diagnostyki
const diagnosticResults = ref([])

function runDiagnostics() {
  diagnosticResults.value = [
    diagnoseValue(systemName, 'systemName'),
    diagnoseValue(isPowered, 'isPowered'),
    diagnoseValue(powerLevel, 'powerLevel'),
    diagnoseValue(systemConfig, 'systemConfig'),
    diagnoseValue(systemConfig.sensors, 'systemConfig.sensors'),
    diagnoseValue(normalString, 'normalString'),
    diagnoseValue(normalNumber, 'normalNumber'),
    diagnoseValue(normalObject, 'normalObject')
  ]
}

// Przykład użycia unref()
function getValue(maybeRef) {
  // unref() bezpiecznie wyciąga wartość z ref lub zwraca normalną wartość
  return unref(maybeRef)
}

// Funkcja uniwersalna przyjmująca ref lub wartość
function updatePowerLevel(newLevel) {
  // Sprawdzamy czy to ref
  if (isRef(powerLevel)) {
    powerLevel.value = newLevel
  } else {
    console.log('powerLevel is not a ref!')
  }
}

// Funkcja uniwersalna dla obiektów
function updateSystemStatus(system, status) {
  if (isReactive(system)) {
    system.online = status
  } else {
    console.log('System is not reactive!')
  }
}

// Przykłady praktyczne
const mixedData = ref([
  { name: 'Sensor A', value: ref(100) },
  { name: 'Sensor B', value: 200 },
  { name: 'Sensor C', value: ref(300) }
])

function processValue(item) {
  // Używamy unref() aby bezpiecznie pobrać wartość
  const value = unref(item.value)
  return value * 1.1
}

// Uruchom diagnostykę przy załadowaniu
runDiagnostics()
</script>

<template>
  <div class="diagnostics">
    <div class="header">
      <h1>DIAGNOSTYKA SYSTEMÓW - NOVA LAB</h1>
      <p class="subtitle">isRef(), isReactive(), unref() - Sprawdzanie reaktywności</p>
    </div>

    <div class="system-panel">
      <h2>System Status</h2>
      <div class="status-grid">
        <div class="status-item">
          <div class="label">System Name</div>
          <div class="value">{{ systemName }}</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">Power Status</div>
          <div class="value">{{ isPowered ? 'ONLINE' : 'OFFLINE' }}</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">Power Level</div>
          <div class="value">{{ powerLevel }}%</div>
          <div class="type-badge ref">REF</div>
        </div>

        <div class="status-item">
          <div class="label">System ID</div>
          <div class="value">{{ systemConfig.id }}</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>

        <div class="status-item">
          <div class="label">Temperature</div>
          <div class="value">{{ systemConfig.sensors.temperature }}°C</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>

        <div class="status-item">
          <div class="label">Pressure</div>
          <div class="value">{{ systemConfig.sensors.pressure }} bar</div>
          <div class="type-badge reactive">REACTIVE</div>
        </div>
      </div>
    </div>

    <div class="diagnostics-panel">
      <div class="panel-header">
        <h2>Wyniki Diagnostyki Reaktywności</h2>
        <button @click="runDiagnostics" class="btn btn-scan">
          Uruchom ponownie
        </button>
      </div>

      <div class="results-table">
        <div class="table-header">
          <div>Nazwa zmiennej</div>
          <div>isRef()</div>
          <div>isReactive()</div>
          <div>Wartość (unref)</div>
          <div>Typ</div>
        </div>
        <div
          v-for="result in diagnosticResults"
          :key="result.name"
          class="table-row"
        >
          <div class="cell-name">{{ result.name }}</div>
          <div class="cell-check">
            <span v-if="result.isRef" class="check-yes">TRUE</span>
            <span v-else class="check-no">FALSE</span>
          </div>
          <div class="cell-check">
            <span v-if="result.isReactive" class="check-yes">TRUE</span>
            <span v-else class="check-no">FALSE</span>
          </div>
          <div class="cell-value">
            {{ typeof result.rawValue === 'object' ? JSON.stringify(result.rawValue) : result.rawValue }}
          </div>
          <div class="cell-type">{{ result.type }}</div>
        </div>
      </div>
    </div>

    <div class="examples-section">
      <h2>Przykłady praktyczne</h2>

      <div class="example-grid">
        <div class="example-card">
          <h3>unref() - Uniwersalne pobieranie wartości</h3>
          <div class="code-box">
            <pre>function getValue(maybeRef) {
  return unref(maybeRef)
}

const refValue = ref(100)
const normalValue = 200

getValue(refValue)    // 100
getValue(normalValue) // 200</pre>
          </div>
          <div class="demo">
            <p>getValue(powerLevel): <strong>{{ getValue(powerLevel) }}</strong></p>
            <p>getValue(normalNumber): <strong>{{ getValue(normalNumber) }}</strong></p>
          </div>
        </div>

        <div class="example-card">
          <h3>isRef() - Sprawdzanie czy wartość jest ref</h3>
          <div class="code-box">
            <pre>if (isRef(value)) {
  value.value = newValue
} else {
  // obsłuż normalną wartość
}</pre>
          </div>
          <div class="demo">
            <p>isRef(powerLevel): <strong class="check-yes">{{ isRef(powerLevel) }}</strong></p>
            <p>isRef(normalNumber): <strong class="check-no">{{ isRef(normalNumber) }}</strong></p>
            <button @click="updatePowerLevel(90)" class="btn btn-small">
              Ustaw moc na 90%
            </button>
          </div>
        </div>

        <div class="example-card">
          <h3>isReactive() - Sprawdzanie czy obiekt jest reactive</h3>
          <div class="code-box">
            <pre>if (isReactive(obj)) {
  obj.property = newValue
} else {
  // obsłuż normalny obiekt
}</pre>
          </div>
          <div class="demo">
            <p>isReactive(systemConfig): <strong class="check-yes">{{ isReactive(systemConfig) }}</strong></p>
            <p>isReactive(normalObject): <strong class="check-no">{{ isReactive(normalObject) }}</strong></p>
            <button @click="updateSystemStatus(systemConfig, !systemConfig.online)" class="btn btn-small">
              Toggle system status
            </button>
          </div>
        </div>

        <div class="example-card">
          <h3>Mieszane dane - praktyczny przypadek</h3>
          <div class="code-box">
            <pre>// Niektóre wartości to ref, inne nie
const sensors = [
  { name: 'A', value: ref(100) },
  { name: 'B', value: 200 }
]

// unref() radzi sobie z obiema
sensors.forEach(s => {
  const val = unref(s.value)
})</pre>
          </div>
          <div class="demo">
            <div v-for="item in mixedData" :key="item.name" class="sensor-item">
              <span>{{ item.name }}:</span>
              <span class="sensor-value">{{ processValue(item) }}</span>
              <span v-if="isRef(item.value)" class="type-badge ref">REF</span>
              <span v-else class="type-badge normal">NORMAL</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="info-box">
      <h3>Kiedy używać tych funkcji?</h3>
      <ul>
        <li>
          <strong>isRef(value):</strong> Sprawdza czy wartość jest ref. Przydatne w funkcjach uniwersalnych.
        </li>
        <li>
          <strong>isReactive(value):</strong> Sprawdza czy obiekt jest reactive. Pomaga w debugowaniu.
        </li>
        <li>
          <strong>unref(value):</strong> Zwraca wartość z ref lub oryginalną wartość. Bezpieczny sposób na dostęp.
        </li>
        <li>
          <strong>Praktyczne zastosowanie:</strong> Tworzenie funkcji kompatybilnych z ref i normalnymi wartościami.
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.diagnostics {
  min-height: 100vh;
  background: #0a0e27;
  color: #e0e0e0;
  padding: 2rem;
  font-family: 'Courier New', monospace;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
  border-bottom: 2px solid #00ff88;
  padding-bottom: 1rem;
}

.header h1 {
  color: #00ff88;
  font-size: 2rem;
  margin: 0;
  text-shadow: 0 0 10px #00ff88;
}

.subtitle {
  color: #00b4d8;
  margin: 0.5rem 0 0 0;
}

.system-panel {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #00b4d8;
  margin-bottom: 2rem;
}

.system-panel h2 {
  color: #00b4d8;
  margin-top: 0;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.status-item {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 6px;
  position: relative;
}

.label {
  font-size: 0.85rem;
  color: #888;
  margin-bottom: 0.5rem;
}

.value {
  font-size: 1.3rem;
  color: #00ff88;
  font-weight: bold;
}

.type-badge {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: bold;
}

.type-badge.ref {
  background: #00b4d8;
  color: #0a0e27;
}

.type-badge.reactive {
  background: #00ff88;
  color: #0a0e27;
}

.type-badge.normal {
  background: #666;
  color: white;
}

.diagnostics-panel {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #00ff88;
  margin-bottom: 2rem;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.panel-header h2 {
  color: #00ff88;
  margin: 0;
}

.btn {
  padding: 0.6rem 1.2rem;
  font-size: 0.9rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  font-family: 'Courier New', monospace;
}

.btn-scan {
  background: linear-gradient(135deg, #00ff88, #00b4d8);
  color: #0a0e27;
}

.btn-scan:hover {
  transform: scale(1.05);
  box-shadow: 0 0 20px #00ff88;
}

.btn-small {
  padding: 0.5rem 1rem;
  font-size: 0.85rem;
}

.results-table {
  background: #0a0e27;
  border-radius: 6px;
  overflow: hidden;
}

.table-header, .table-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 2fr 1fr;
  gap: 1rem;
  padding: 1rem;
  align-items: center;
}

.table-header {
  background: #00ff8820;
  color: #00ff88;
  font-weight: bold;
  border-bottom: 2px solid #00ff88;
}

.table-row {
  border-bottom: 1px solid #333;
}

.table-row:hover {
  background: #1a1f3a;
}

.cell-name {
  color: #00b4d8;
  font-family: monospace;
}

.cell-check {
  text-align: center;
}

.check-yes {
  color: #00ff88;
}

.check-no {
  color: #666;
}

.cell-value {
  color: #ccc;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cell-type {
  color: #888;
  font-style: italic;
}

.examples-section {
  margin-bottom: 2rem;
}

.examples-section h2 {
  color: #00ff88;
  margin-bottom: 1.5rem;
}

.example-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 1.5rem;
}

.example-card {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border: 1px solid #333;
}

.example-card h3 {
  color: #00b4d8;
  margin-top: 0;
  font-size: 1.1rem;
}

.code-box {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 4px;
  border-left: 3px solid #00ff88;
  margin: 1rem 0;
}

.code-box pre {
  margin: 0;
  color: #00ff88;
  font-size: 0.85rem;
  overflow-x: auto;
}

.demo {
  background: #0a0e27;
  padding: 1rem;
  border-radius: 4px;
}

.demo p {
  margin: 0.5rem 0;
  color: #ccc;
}

.demo strong {
  color: #00ff88;
}

.sensor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  margin: 0.3rem 0;
  background: #1a1f3a;
  border-radius: 4px;
}

.sensor-value {
  color: #00ff88;
  font-weight: bold;
}

.info-box {
  background: #1a1f3a;
  padding: 1.5rem;
  border-radius: 8px;
  border-left: 4px solid #00ff88;
}

.info-box h3 {
  color: #00ff88;
  margin-top: 0;
}

.info-box ul {
  color: #ccc;
  line-height: 1.8;
}

.info-box strong {
  color: #00b4d8;
}
</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. Co się stanie przy destructuringu obiektu reactive: const { name } = state?

  2. 2. Co robi toRef(state, 'name')?

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

Zadania praktyczne w grze

  • Edytor kodu

    Użyj toRef() do stworzenia reaktywnej referencji do właściwości reactive.

  • Klikanie w kolejności

    Ułóż poprawne użycie toRef():

  • Edytor kodu

    Użyj toRefs() do bezpiecznego destructuringu obiektu reactive.

  • Układanie w pionie

    Ułóż kroki bezpiecznego destructuringu reactive:

  • Układanie w poziomie

    Ułóż składnię destructuringu z toRefs:

  1. PytanieProblem z destructuring reactive
  2. PytanieFunkcja toRef()
  3. Zadanie z kodemPraktyka: toRef() pojedyncza właściwość
  4. Kliknij w kolejnościSkładnia toRef
  5. PytanieFunkcja toRefs()
  6. Zadanie z kodemPraktyka: toRefs() destrukturyzacja
  7. Ułóż w kolejnościProces destructuringu z toRefs
  8. Ułóż w kolejnościDestructuring z toRefs
  9. PytanietoRef vs toRefs

Przydatne artykuły