SoFunction
Updated on 2025-04-05

Summary of the usage and differences between ref and reactive in front-end vue3

The difference between ref and reactive

Different types of received values

  • refrefCan be processedValues ​​of the base type, can also be processedValue of reference type
const ref1 = ref(0)            // true
const ref2 = ref({ count: 0 }) // true

When used to create a responsive basic data type, such as numbers, strings, etc. It turns ordinary data into responsive data, which can monitor changes in data. userefWhen we can pass.valueto access and modify the value of the data.

  • reactivereactiveOnly values ​​of reference types are processed, and values ​​of the underlying type are not allowed to be passed.
const reactive1 = reactive(0)            // false
const reactive2 = reactive({ count: 0 }) // true

reactiveUsed to create a responsive object that can contain multiple properties. Through reactive, we can turn the entire object into a responsive form, so that any property of the object can be detected when it changes.

Different ways to access data

ForrefFor example, whether it is a primitive type or an object, accessing data needs to be passed..valueIn the form of the data, the update of the data also needs to be passed.valueCome update.

<template>
      <div>{{ dxc }}</div>
</template>
 
<script setup>
    import { ref } from 'vue'
    const dxc = ref(0)
</script>

But in<template>When using the value of ref, you do not need to bring it with you..value

const ref1 = ref(0) 
()  // 0
 
const ref2 = ref({ count: 0 })
()  // 0
 
 = 1
()  // 1

Watch monitoring methods are different

  • refYou can directly listen to the data, and when the data changes, it will be executed.watchThe callback corresponding to the function.
const ref1 = ref(0)
watch(ref1, () => { 
  ('changed!')
})

It's just herePrimitive type data,in the case ofObjectIn-depth monitoring is requireddeep:true

const ref1 = ref({num: 1})
watch(ref1, () =&gt; { 
    ('changed!')
})
 
//  = 1 
// Watch listening will not be triggered when executing this statement, watch does not perform deep monitoring of ref1// But note that at this time the dom can be updated, and ref will convert it into reactive form 
// To listen in depth, you only need to add a corresponding parameterconst ref1 = ref({num: 1})
watch(ref1, () =&gt; { 
    ('changed!')
}, { deep: true })
  • reactiveBecause essence is an object, it will instinctively add it when watching.deepAttributes. vue optimized itwatchYou can not add it when listening to reactivedeepIt can also be monitored in depth.
const reactive1 = reactive({num: 1})
watch(reactive1, () =&gt; { 
    ('changed!')
})
//  = 1
// Trigger watch monitoring

Basic usage of Ref and its use in setup()

Basic usage

existVue3middle,refUsed to create a responsive basic data type, such as numbers, strings, etc. passref()Function creates arefobject can then pass.valueto access and modify data values.

import { ref } from 'vue';

const count = ref(0); // Create a Ref object with an initial value of 0(); // Access the value of the Ref object = 1; // Modify the value of the Ref object

Use in setup()

existsetup()In the function, we can useref()to create responsive data for use in components.

import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);
    return {
      count
    };
  }
};

<script setup>Syntax is a concise way of writing that can be used more easily in single file componentsref

<script setup>
import { ref } from 'vue';

const count = ref(0);
</script>

Basic concepts of Reactive and their use in templates

Basic concepts

existVue3middle,reactiveUsed to create a responsive object that allows the object's properties to be detected when they change. passreactive()A function creates a responsive object, and all properties of the object become responsive.

import { reactive } from 'vue';

const user = reactive({
  name: 'Alice',
  age: 30
});

Using Reactive in Template

You can directly use responsive objects in the template to access and modify the properties of the object.

<template>
  <div>
    <p>Name: {{  }}</p>
    <p>Age: {{  }}</p>
  </div>
</template>

<script>
import { reactive } from 'vue';

export default {
  setup() {
    const user = reactive({
      name: 'Alice',
      age: 30
    });

    return { user };
  }
};
</script>

Summary of the usage of ref and reactive

ref

  • Basic usageRefUsed to create a responsive basic data type, such as numbers, strings, etc. passrefFunction creation, access and modify data values ​​need to be used.value
  • Use in setup():existsetup()In the function, we can userefto create responsive data and use it in templates.
  • <script setup> Syntax<script setup>Syntax is a recommended writing method in Vue3, which allows you to use ref more concisely in single-file components.
  • Why use refRefSuitable for managing simple basic data types, such as numbers, strings, etc.

reactive

  • Basic conceptsReactiveUsed to create a responsive object that can contain multiple properties. passreactiveFunction creation, any property changes of the object will be detected.
  • Use in templatesReactive: You can directly use responsive objects in the template to access and modify the properties of the object.
  • Deep responsiveReactiveRecursively convert all nested properties of the object into responsive.
  • Difference from refRefSuitable for simple data types, andReactiveApplicable to objects, can handle multiple properties of an object.
  • Why useReactiveReactiveSuitable for managing complex objects, making the entire object responsive.

Attachment: Comparison of ref and reactive definition arrays

Use ref to define an array

const tableData = ref([]) // Definition
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi() // Simulate the interface to obtain table data	 = data // Revise}
&lt;!-- Vue3Template reference usage --&gt;
&lt;a-table v-model:dataSource="tableData"&gt;&lt;/a-table&gt;

The figure takes our commonly used tabular data as an example. You can see that there is no difference between defining an array of ref and defining a basic data type. Let's take a look at reactive

const tableData = reactive([]) // Definition
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi() // Simulate the interface to obtain table data	tableData = data // Modify, error example, so assignment will cause tableData to lose its responsiveness}
&lt;!-- Vue3Template reference usage --&gt;
&lt;a-table v-model:dataSource="tableData"&gt;&lt;/a-table&gt;

It should be noted that using the modification method of tableData = data will cause the responsive loss of tableData. The solution is as follows (for reference)

// Method 1: Change to ref definitionconst tableData = ref([])
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi()
	 = data // Reassign value using .value}
// Method 2: Use push methodconst tableData = reactive([])
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi()
	(...data) // Deconstruct data first using..., and then use push method}
// Method 3: Nesting an object outside the array when definingconst tableData = reactive({ list:[] })
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi()
	 = data //Reassign value by accessing the list attribute}
// Method 4: Pack another layer of reactive before assignmentconst tableData = reactive([])
const getTableData = async () =&gt; {
	const { data } = await getTableDataApi()
	tableData = reactive(data) //Another layer of reactive is included before assignment}

Summarize

This is the article about the usage and differences between ref and reactive in front-end vue3. For more related ref and reactive content in vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!