ref/reactive in depth
ref suits single values and reassignments while reactive suits objects, and each has its own gotchas.
In this page:
Syntax
const count = ref(0); // access with .value in script
count.value++;
const state = reactive({ count: 0 }); // access properties directly
state.count++;
ref/reactive in depth
ref works for primitives and objects and always needs .value in script. reactive proxies objects and loses reactivity if you reassign or destructure it.
A common pattern is ref for simple values and reactive for grouped state, or ref everywhere for consistency. isRef, unref and toRaw help in edge cases.
Note:
Many teams choose ref everywhere for consistent behaviour.
Example: ref/reactive in depth
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"><p>{{ a }} {{ obj.x }} {{ info }}</p></div>
<script>
Vue.createApp({
setup() {
const a = Vue.ref(1);
const obj = Vue.reactive({ x: 10 });
const { x } = obj; // plain copy: no longer reactive
obj.x = 11;
const objRef = Vue.ref({ y: 1 });
objRef.value.y++;
const info = `x copy=${x}, obj.x=${obj.x}, isRef=${Vue.isRef(a)}, unref=${Vue.unref(a)}, y=${objRef.value.y}`;
console.log(info);
return { a, obj, info };
},
}).mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: 1 11 x copy=10, obj.x=11, isRef=true, unref=1, y=2
console: x copy=10, obj.x=11, isRef=true, unref=1, y=2
-->
Live Example
Related Topics
Common Mistakes
- Reassigning a reactive variable
- Forgetting .value
- Destructuring reactive objects
Chapter Summary
- ref needs .value
- reactive proxies objects
- Reassigning or destructuring reactive breaks it
- unref and isRef help
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: