Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

toRef i toRefs - Bezpieczne Rozpakowywanie Sensorów

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.

Problem z Destructuring

1import { reactive } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500
6})
7
8// ŹLE - traci reaktywność!
9const { name, temperature } = reactor
10console.log(name) // 'Plasma Core Alpha' - ale nie jest reaktywny
11
12reactor.name = 'Plasma Core Beta'
13console.log(name) // Nadal 'Plasma Core Alpha'!

toRef() - Pojedynczy Sensor

1import { reactive, toRef } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500
6})
7
8// toRef tworzy reaktywną referencję do odczytu
9const nameRef = toRef(reactor, 'name')
10
11console.log(nameRef.value) // 'Plasma Core Alpha'
12
13reactor.name = 'Plasma Core Beta'
14console.log(nameRef.value) // 'Plasma Core Beta' - zsynchronizowane!
15
16nameRef.value = 'Plasma Core Gamma'
17console.log(reactor.name) // 'Plasma Core Gamma' - dwukierunkowe!

toRefs() - Wszystkie Sensory

1import { reactive, toRefs } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500,
6  status: 'ACTIVE'
7})
8
9// toRefs konwertuje wszystkie właściwości
10const { name, temperature, status } = toRefs(reactor)
11
12// Każda jest teraz ref z .value
13console.log(name.value) // 'Plasma Core Alpha'
14console.log(temperature.value)  // 2500
15
16// Zmiany są zsynchronizowane
17reactor.temperature = 2600
18console.log(temperature.value) // 2600

Użycie w Komponentach

1<template>
2  <div>
3    <input v-model="title" />
4    <p>Rok: {{ year }}</p>
5  </div>
6</template>
7
8<script setup>
9import { reactive, toRefs } from 'vue'
10
11const artwork = reactive({
12  title: 'Mona Lisa',
13  year: 1503
14})
15
16// Rozpakuj do użycia w template
17const { title, year } = toRefs(artwork)
18</script>

toRef z Domyślną Wartością

1import { reactive, toRef } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha'
5  // brak 'maxTemperature'
6})
7
8// Z wartością domyślną (Vue 3.3+)
9const maxTemperature = toRef(reactor, 'maxTemperature', 5000)
10console.log(maxTemperature.value) // 5000

Praktyczny Przykład - Props

1<!-- SensorDisplay.vue -->
2<script setup>
3import { toRefs } from 'vue'
4
5const props = defineProps<{
6  sensorName: string
7  reading: number
8}>()
9
10// Rozpakuj props z zachowaniem reaktywności
11const { sensorName, reading } = toRefs(props)
12
13// Teraz możesz użyć w watch, computed itp.
14</script>
Vai a CodeWorlds