The difference between ref() and reactive() in vue3

Vue3 provides two ways to declare responsive data: ref() and reactive().

reactive

The reactive() function is used to create a reactive object or array, and returns a Proxy of the original object. The reactive() API has two limitations:

  1. Valid only for object types (objects, arrays, and collection types like Map and Set), not primitive types like string, number, and boolean.
  2. It is not possible to arbitrarily "replace" a reactive object, which would cause the reactive connection to the original reference to be lost. When we assign or destructure a property of a reactive object to a local variable, or pass that property into a function, it loses responsiveness.
let state = reactive({
    
     count: 0 })
// 上面的引用 ({ count: 0 }) 将不再被追踪(响应性连接已丢失!)
state = reactive({
    
     count: 1 })

// n 是一个局部变量,同 state.count 失去响应性连接
let n = state.count
// 不影响原始的 state
n++

// count 也和 state.count 失去了响应性连接
let {
    
     count } = state
// 不会影响原始的 state
count++

// 该函数接收一个普通数字,并且将无法跟踪 state.count 的变化
callSomeFunction(state.count)

ref

The ref() method is used to create a reactive variable that can use any value type, returning a reactive ref object based on that value. ref() wraps the value of the incoming parameter into a ref object with a .value attribute, and the .value attribute of ref is also responsive. At the same time, when the value of the parameter is an object type, its .value will be automatically converted with reactive().

  1. A ref containing a value of type object can reactively replace the entire object.
const objectRef = ref({
    
     count: 0 })
// 这是响应式的替换
objectRef.value = {
    
     count: 1 }
  1. refs are passed to functions or destructured from regular objects without losing reactivity. ref() allows us to create "references" to arbitrary values ​​and pass them around without losing responsiveness.
const obj = {
    
    
  foo: ref(1),
  bar: ref(2)
}

// 该函数接收一个 ref,需要通过 .value 取值,但它会保持响应性
callSomeFunction(obj.foo)

// 仍然是响应式的
const {
    
     foo, bar } = obj

Summarize

Both reactive() and ref() are used to define reactive data. The reactive() parameter generally accepts objects or arrays, which is a deep responsive type. The ref() parameter generally accepts a simple data type. If ref() accepts an object as a parameter, it will essentially be transformed into a reactive method. The essence of ref() and reactive() can be simply understood as ref is a secondary packaging for reactive.

Guess you like

Origin blog.csdn.net/weixin_39964419/article/details/128718376