The difference between ref and reactive
Different types of received values
-
ref:
ref
Can 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. useref
When we can pass.value
to access and modify the value of the data.
-
reactive:
reactive
Only 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
reactive
Used 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
Forref
For example, whether it is a primitive type or an object, accessing data needs to be passed..value
In the form of the data, the update of the data also needs to be passed.value
Come 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
-
ref
You can directly listen to the data, and when the data changes, it will be executed.watch
The 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, () => { ('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, () => { ('changed!') }, { deep: true })
-
reactive
Because essence is an object, it will instinctively add it when watching.deep
Attributes. vue optimized itwatch
You can not add it when listening to reactivedeep
It can also be monitored in depth.
const reactive1 = reactive({num: 1}) watch(reactive1, () => { ('changed!') }) // = 1 // Trigger watch monitoring
Basic usage of Ref and its use in setup()
Basic usage
existVue3
middle,ref
Used to create a responsive basic data type, such as numbers, strings, etc. passref()
Function creates aref
object can then pass.value
to 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
existVue3
middle,reactive
Used 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 usage:
Ref
Used to create a responsive basic data type, such as numbers, strings, etc. passref
Function creation, access and modify data values need to be used.value
。- Use in setup():exist
setup()
In the function, we can useref
to 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 ref:
Ref
Suitable for managing simple basic data types, such as numbers, strings, etc.
reactive
- Basic concepts:
Reactive
Used to create a responsive object that can contain multiple properties. passreactive
Function creation, any property changes of the object will be detected.- Use in templates
Reactive
: You can directly use responsive objects in the template to access and modify the properties of the object.- Deep responsive:
Reactive
Recursively convert all nested properties of the object into responsive.- Difference from ref:
Ref
Suitable for simple data types, andReactive
Applicable to objects, can handle multiple properties of an object.- Why use
Reactive
:Reactive
Suitable 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 () => { const { data } = await getTableDataApi() // Simulate the interface to obtain table data = data // Revise}
<!-- Vue3Template reference usage --> <a-table v-model:dataSource="tableData"></a-table>
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 () => { 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}
<!-- Vue3Template reference usage --> <a-table v-model:dataSource="tableData"></a-table>
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 () => { const { data } = await getTableDataApi() = data // Reassign value using .value} // Method 2: Use push methodconst tableData = reactive([]) const getTableData = async () => { 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 () => { 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 () => { 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!