Technology Sharing

Responsive ref() and reactive()

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


ref()

  • effect: Define the response variable.

  • grammar:let xxx=ref(initial value).

  • return value: An instance object of RefImpl, referred to as ref object or ref, the value attribute of the ref object is responsive

  • be careful

    1. In JS, data operation requires: xxx.value, but in the template, .value is not required and can be used directly.
    2. For let name =ref('张三'), name is not responsive, but name.value is responsive

reactive()

  • effect: Define a responsive object (don’t use it for basic types, use ref, otherwise an error will be reported).

  • grammar:let responsive object = reactive(source object).

  • return value: A Proxy instance object, also known as a responsive object.

  • be careful: The responsive data defined by reactive is "deep".

ref vs reactive

  • From a macro perspective:
    1. ref is used to define: basic type data, object type data;
    2. reactive is used to define: object type data.
  • the difference:
    1. Variables created by ref must use,value (,value,can be added automatically using the volar plugin).
    2. reactive reallocates a new object and loses responsiveness (you can use Object.assign to replace the entire object).
  • Principles of use:
    1. If you need a basic type of responsive data, you must use ref.
    2. If a responsive object is needed and the hierarchy is not deep, both ref and reactive can be used.
    3. If a responsive object is needed and the hierarchy is deep, it is recommended to use reactive.

toRefs vs toRef

effect: Convert each property in a responsive object into a ref object.
Remark: toRefs has the same function as toRef, but toRefs can perform batch conversion.
The syntax is as follows:

import {reactive,toRefs,toRef} from
// 数据
let person = reactive({
	name:'张三
	age:18
})
let {name,age} = toRefs(person)
let nl = toRef(person,'age')