We use cookies to enhance your experience on the site
CodeWorlds

toRef and toRefs - Safe Sensor Unpacking

Sometimes you need to extract individual properties from a reactive sensor object while preserving reactivity - like isolating specific readings from a complex monitoring system.

The Destructuring Problem

1import { reactive } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500
6})
7
8// BAD - loses reactivity!
9const { name, temperature } = reactor
10console.log(name) // 'Plasma Core Alpha' - but not reactive
11
12reactor.name = 'Plasma Core Beta'
13console.log(name) // Still 'Plasma Core Alpha'!

toRef() - Single Sensor

1import { reactive, toRef } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500
6})
7
8// toRef creates a reactive reference to a reading
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' - synchronized!
15
16nameRef.value = 'Plasma Core Gamma'
17console.log(reactor.name) // 'Plasma Core Gamma' - bidirectional!

toRefs() - All Sensors

1import { reactive, toRefs } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha',
5  temperature: 2500,
6  status: 'ACTIVE'
7})
8
9// toRefs converts all properties
10const { name, temperature, status } = toRefs(reactor)
11
12// Each is now a ref with .value
13console.log(name.value) // 'Plasma Core Alpha'
14console.log(temperature.value)  // 2500
15
16// Changes are synchronized
17reactor.temperature = 2600
18console.log(temperature.value) // 2600

Usage in Components

1<template>
2  <div>
3    <input v-model="title" />
4    <p>Year: {{ 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// Unpack for use in template
17const { title, year } = toRefs(artwork)
18</script>

toRef with Default Value

1import { reactive, toRef } from 'vue'
2
3const reactor = reactive({
4  name: 'Plasma Core Alpha'
5  // no 'maxTemperature'
6})
7
8// With default value (Vue 3.3+)
9const maxTemperature = toRef(reactor, 'maxTemperature', 5000)
10console.log(maxTemperature.value) // 5000

Practical Example - Props

1<!-- SensorDisplay.vue -->
2<script setup>
3import { toRefs } from 'vue'
4
5const props = defineProps<{
6  sensorName: string
7  reading: number
8}>()
9
10// Unpack props while preserving reactivity
11const { sensorName, reading } = toRefs(props)
12
13// Now you can use them in watch, computed, etc.
14</script>
Go to CodeWorlds