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.

1
import { ref } from "vue";
2
3
const count = ref(0); // Creating a reactive primitive type
4
console.log(count.value); // Access its value using .value
5
6
count.value++; // Update value through .value

What 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.

1
import { reactive, toRef } from "vue";
2
3
const state = reactive({ name: "Alice", age: 25 });
4
const nameRef = toRef(state, "name"); // Convert a property of the object into a ref
5
6
console.log(nameRef.value); // Access the name property
7
nameRef.value = "Bob"; // Update the name property

What 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.

1
import { reactive, toRefs } from "vue";
2
3
const state = reactive({ name: "Alice", age: 25 });
4
const { name, age } = toRefs(state); // Convert all properties of the object into refs
5
6
console.log(name.value); // Access the name property
7
name.value = "Bob"; // Update the name property

Summary

  • ref: Creates a reactive value suitable for both primitive and object types.
  • toRef: Converts a single property of an object into a ref, allowing independent reactivity for that property.
  • toRefs: Converts all properties of an object into ref, 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.