We use cookies to enhance your experience on the site
CodeWorlds

reactive() - Reactive Systems

When working with complex system objects,

reactive()
is often more convenient than
ref()
- it's like a complete reactor control panel instead of individual gauges.

Basics of 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// Access without .value!
14console.log(reactor.name) // 'Plasma Core Alpha'
15reactor.temperature = 2600
16
17// Nested objects are also reactive
18reactor.readings.power = 900 // This will also trigger a panel update

reactive() vs ref()

| Feature | ref() | reactive() | |-------|-------|------------| | For primitives | Yes | No | | For objects | Yes (.value) | Yes (directly) | | Destructuring | Safe | Loses reactivity | | Reassign | Yes (.value = newObj) | No (only properties) |

Practical Example

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>Temperature: {{ reactor.temperature }} K</p>
6    <p>Readings: {{ reactor.readings.power }} MW | {{ reactor.readings.radiation }} Sv/h</p>
7
8    <button @click="updateTemperature">Increase temperature</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 // Direct modification
27}
28</script>

Limitations of reactive()

1import { reactive } from 'vue'
2
3const reactor = reactive({ name: 'Plasma Core Alpha' })
4
5// BAD - replacing the entire object
6reactor = { name: 'Plasma Core Beta' } // This won't work!
7
8// GOOD - modifying properties
9reactor.name = 'Plasma Core Beta'
10
11// BAD - destructuring loses reactivity
12const { name } = reactor // name is not reactive!
13
14// GOOD - use toRefs
15import { toRefs } from 'vue'
16const { name } = toRefs(reactor) // name.value is reactive
Go to CodeWorlds