SoFunction
Updated on 2025-04-05

Detailed explanation of reactive data ref and reactive in

The Composition API was introduced, whichrefandreactiveare two important functions used to create responsive data. In this blog, we will explore in-depth the differences and usage scenarios in practical applications.

1. ref: Processing responsive data of basic data types

refMainly used to create responsive data that wraps basic data types. passref, We can wrap basic data types such as numbers, strings, and booleans in an object for responsive processing.

import { ref } from 'vue';
// Create responsive data using refconst count = ref(0);
// Access the value of ref(); // Output: 0// Modify the value of ref++;

In the above example, we userefCreate a responsive object that wraps numberscount. Note, access and modifyrefThe value of.value

2. reactive: Process responsive data of object type

By comparison,reactiveMore suitable for processing responsive data of object types. passreactive, we can turn the entire object into a responsive form, including all the properties of the object. (Similar to vue2's data function)

import { reactive } from 'vue';
// Create reactive objects using reactiveconst state = reactive({
  message: 'Hello Vue',
  nested: {
    value: 42
  }
});
// Direct access to the properties of the reactive object(); // Output: Hello Vue// Modify the properties of the reactive object = 'Vue 3 is awesome';
// Access nested properties(); // Output: 42

In the above example, we usereactiveCreated a responsive objectstate, which contains a string propertymessageand a nested object propertynested

3. How to choose: ref or reactive?

  • userefWhen you work with basic data types, such as numbers, strings, or booleans.
  • usereactiveWhen you deal with object types, you need to make all the properties of the object responsive.

In actual development, you may use it at the same timerefandreactive, select the appropriate API according to the characteristics of the data. This flexibility is an advantage of the 3 Composition API, making managing component state more intuitive and convenient.

To sum up,refandreactiveare two key functions in 3 to create responsive data. They are suitable for different types of data, helping us better organize and manage the state of components.

This is the article about reactive data: ref and reactive. For more related reactive data ref and reactive content, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!