In-depth Understanding of ref, toRef, and toRefs in Vue 3
- 348Words
- 2Minutes
- 26 Aug, 2024
In Vue 3’s Composition API, ref, toRef, and toRefs are crucial reactive tools. These APIs allow you to handle reactive data in a more flexible way, especially when fine-grained control over reactive states is needed.
What is ref?
ref is an API in Vue 3 used to create reactive data. It can wrap any type of value, whether primitive or object. Reactive data created with ref returns an object with a .value property, through which we access or modify the data.
1import { ref } from "vue";2
3const count = ref(0); // Creating a reactive primitive type4console.log(count.value); // Access its value using .value5
6count.value++; // Update value through .valueWhat is toRef?
toRef is used to convert a property of an object into a ref, making that property reactive without making the entire object reactive. This is useful when dealing with complex objects, especially when you only want to manipulate a single property reactively.
1import { reactive, toRef } from "vue";2
3const state = reactive({ name: "Alice", age: 25 });4const nameRef = toRef(state, "name"); // Convert a property of the object into a ref5
6console.log(nameRef.value); // Access the name property7nameRef.value = "Bob"; // Update the name propertyWhat is toRefs?
toRefs converts every property of an object into ref, allowing us to deconstruct the object or use its properties individually in templates while retaining reactivity.
1import { reactive, toRefs } from "vue";2
3const state = reactive({ name: "Alice", age: 25 });4const { name, age } = toRefs(state); // Convert all properties of the object into refs5
6console.log(name.value); // Access the name property7name.value = "Bob"; // Update the name propertySummary
ref: Creates a reactive value suitable for both primitive and object types.toRef: Converts a single property of an object into aref, allowing independent reactivity for that property.toRefs: Converts all properties of an object intoref, useful when deconstructing the object while retaining reactivity.
These APIs offer more flexible reactive handling in Vue 3, enabling fine-grained control and management of component states. During development, you can choose the appropriate API based on your needs to optimize code structure and reactive performance.