Skip to content

Instantly share code, notes, and snippets.

@Bazsmagister
Created July 9, 2024 06:20
Show Gist options
  • Save Bazsmagister/1a3c59d1e8524a33f747c6f5a2196e81 to your computer and use it in GitHub Desktop.
Save Bazsmagister/1a3c59d1e8524a33f747c6f5a2196e81 to your computer and use it in GitHub Desktop.
vu3 toRef() vs toRefs()
https://vuejs.org/api/reactivity-utilities.html#toref
https://vuejs.org/api/reactivity-utilities.html#torefs
In Vue 3, both toRef() and toRefs() are part of the Composition API and serve different purposes:
toRef():
Converts a single reactive object property to a ref that maintains its connection with the parent object.
Example:
const state = reactive({ foo: 1, bar: 2 });
const fooRef = toRef(state, 'foo'); // fooRef: Ref<number>
If state.foo changes, fooRef.value will change as well.
Useful when you want to copy a value property from an object and maintain its reactivity.
toRefs():
Converts all properties of a reactive object to a new plain object
where each property is a ref pointing to the corresponding property of the original object.
Example:
const state = reactive({ foo: 1, bar: 2 });
const stateAsRefs = toRefs(state); // { foo: Ref<number>, bar: Ref<number> }
Useful when destructuring a reactive object (e.g., from a composable)
and needing individual refs for each property.
Remember that toRef is for a single property, while toRefs is for all properties of an object1.
If you’re working with non-object variables, use toRef.
If you’re destructuring an object, consider using toRefs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment