reactive
method creates and returns adeeply responsive object(Proxy proxy object) based on the incoming object.
reactive
will wrap the incomingobjectand create aProxy proxy object
for the object. It is a reactive copy of thesource object and is not equal to the original object. It == "deeply" == converts all nested properties
of the source object, unpacking and maintaining any ref references within them.
Responsive object attribute value changes will trigger responsiveness no matter how deep the level is. Adding and deleting attributes will also trigger reactivity.
ref
function is used to package an item of data intoa responsive ref object. It receives parameters of any data type as the value of thevalue property
inside this ref object.
Generate value type data (String
,Number
,Boolean
,Symbol
) Reactive objects
can access or change this value usingref object.value
.
Generate responsive objects of object and array types(Objects and arrays generally do not use ref mode, but reactive mode, which is more convenient)
Comparison from the perspective of definition data:
ref is used to define:Any data type
reactive is used to define:Object (or array) type data
How to choose ref and reactive? Suggestion:
Basic type values (String, Number, Boolean, Symbol) or single-value objects (objects with only one attribute value like {count: 1}) use ref
Use reactive for reference type values (Object, Array)
getand
setof
Object.defineProperty().
Proxy, and operates
source objectinternally through
ReflectData
##reactive: neither operating data nor reading data requires
5. toRefs
to ref
Note: The reactive object encapsulated by reactive should not be returned directly through destructuring. This is not responsive.It can be processed through toRefs, and then deconstructed and returned, so that it can be responsive
const state = reactive({ age: 20, name: 'zhangsan'}); return {...state}; // 错误的方式,会丢失响应式 return toRefs(state); // 正确的方式 //最佳方式 return ...toRefs(state)//将对象的各个属性的ref解构到对象根下面。
6. Some questions
Why do you still have a reactive function? Do you need the ref function?When we just want a certain variable to be responsive, it will be more troublesome to use reactive. Therefore, vue3 provides the ref method to monitor simple values, but it does not mean that ref can only be passed Enter simple values, and its bottom layer is reactive, so it has everything reactive has.Remember: ref is also reactive in nature, ref(obj) is equivalent to reactive({value: obj})
The above is the detailed content of Summary Vue creates responsive data objects (reactive, ref, toRef, toRefs). For more information, please follow other related articles on the PHP Chinese website!