In Vue.js 3, ref, toRef, and toRefs are APIs used for handling reactive data. These APIs have distinctions when converting primitive data types and object/array types to reactive data.
ref
ref is primarily used to create a reactive data reference. When you pass a primitive data type (such as String, Number, Boolean) to ref, it wraps this primitive data type in an object and makes this object reactive. When the data changes, any views or computed properties using this ref variable will update accordingly.
Example:
javascriptimport { ref } from 'vue'; const count = ref(0); function increment() { count.value++; }
In this example, count is a reactive reference with an initial value of 0. Each time the increment function is called, the value of count increases, and since count is reactive, any views dependent on count will automatically update.
toRef
toRef is used to create a direct reactive reference to a specific property of an object. Unlike ref, toRef does not make the entire object reactive; it only targets a specific property of the object. This is useful when you only need to focus on a single property of the object while keeping the rest unchanged.
Example:
javascriptimport { reactive, toRef } from 'vue'; const state = reactive({ firstName: 'John', lastName: 'Doe' }); const firstNameRef = toRef(state, 'firstName'); // Modifying firstNameRef also affects the original state object firstNameRef.value = 'Jane';
In this example, firstNameRef is a reactive reference to the firstName property of the state object. Modifying firstNameRef directly affects the firstName property in state.
toRefs
toRefs is similar to toRef, but it is used to convert all properties of a reactive object into independent reactive references. This allows you to destructure or pass the properties of the reactive object to other functions without losing reactivity.
Example:
javascriptimport { reactive, toRefs } from 'vue'; const state = reactive({ firstName: 'John', lastName: 'Doe' }); const { firstName, lastName } = toRefs(state); // firstName and lastName are both reactive firstName.value = 'Jane'; lastName.value = 'Smith';
In this example, firstName and lastName become independent reactive references derived from the original reactive object state. This allows you to manipulate each property individually without losing reactivity.
In summary, ref is used for primitive data types or wrapping any value into a reactive object, toRef is used to create a reactive reference for a single property from a reactive object, and toRefs is used to convert all properties of a reactive object into independent reactive references. The usage of these tools depends on your specific needs, such as whether you require overall reactivity or only maintain reactivity for certain properties of the object.