How to Use toRef and toRefs in Vue for Reactive References
In Vue,
toRef creates a reactive reference to a single property of a reactive object, while toRefs converts all properties of a reactive object into reactive references. These helpers let you destructure reactive objects without losing reactivity.Syntax
toRef takes a reactive object and a property key, returning a reactive reference to that property.
toRefs takes a reactive object and returns an object where each property is a reactive reference.
javascript
import { reactive, toRef, toRefs } from 'vue'; const state = reactive({ count: 0, name: 'Vue' }); const countRef = toRef(state, 'count'); const refs = toRefs(state); // refs.count and refs.name are reactive references
Example
This example shows how to use toRef to create a reactive reference to a single property and toRefs to destructure all properties while keeping reactivity.
javascript
import { reactive, toRef, toRefs, watch } from 'vue'; const state = reactive({ count: 0, message: 'Hello' }); // Using toRef for single property const countRef = toRef(state, 'count'); // Using toRefs for all properties const { count, message } = toRefs(state); // Watch changes on countRef watch(countRef, (newVal) => { console.log('countRef changed to', newVal); }); // Update reactive state state.count = 5; console.log(count.value); // 5 console.log(message.value); // 'Hello'
Output
countRef changed to 5
5
Hello
Common Pitfalls
A common mistake is destructuring a reactive object directly without toRefs, which breaks reactivity because the properties become plain values.
Always use toRef or toRefs when destructuring reactive objects to keep reactivity intact.
javascript
import { reactive, toRefs } from 'vue'; const state = reactive({ count: 0 }); // Wrong: destructuring breaks reactivity const { count } = state; // Updating state.count won't update count variable state.count = 10; console.log(count); // still 0 // Correct: use toRefs const { count: reactiveCount } = toRefs(state); state.count = 20; console.log(reactiveCount.value); // 20
Output
0
20
Quick Reference
| Function | Purpose | Input | Output |
|---|---|---|---|
| toRef | Create a reactive ref for a single property | Reactive object, property key | Ref to that property |
| toRefs | Convert all properties to reactive refs | Reactive object | Object with refs for each property |
Key Takeaways
Use toRef to create a reactive reference to one property of a reactive object.
Use toRefs to convert all properties of a reactive object into reactive references.
Destructuring reactive objects without toRefs breaks reactivity.
toRef and toRefs help maintain reactivity when working with reactive state.
Always access reactive references with .value when outside templates.