Ref is a copy of the original data, and when you modify the REF data, the view in the template changes, but the original data does not.

ToRef is a reference to the original data, and when toRef data is modified, the original data is also changed, but the view is not updated.

In VUe3, reactive data of a base type is defined using REF, and reactive data of a reference type is defined using Reactive data.

Import {ref,reactive} from "vue" export default {setup(){let num=ref(0) let obj=reactive({name:' zhang 3 ',age:18}) return {num,obj} } }Copy the code

{{obj. Name}},{{obj. Age}},{{obj.

{{name}} and {{age}} can be used directly in the template. {{name}} can be used directly in the template.

Import {ref,reactive} from "vue" export default {setup(){let num=ref(0) let obj=reactive({name:' zhang ',age:18}) let {name,age}=obj return {num,name,age} } }Copy the code

ToRef is converting a value in an object into a response toRef(obj,key)

Import {toRef} from "vue" export default {setup() {let obj = {name: 'zhang Three ', age: 18}; let newObj = toRef(obj, 'name'); SetTimeout (() => {newobj. value = 'setTimeout '; console.log(obj, newObj); }, 2000); return { obj, newObj }; }}; </script>Copy the code

ToRef is a reference to the original data, and when toRef data is modified, the original data is also changed, but the view is not updated.

ToRefs is converting the whole object into responsive data toRefs(OBJ)

Import {toRefs} from "vue" export default {let obj = {name: 'zhang3 ', age: 18}; let newObj = toRefs(obj); SetTimeout (() => {newobj.name. console.log(obj, newObj); }, 2000); return { obj, newObj }; }Copy the code

It is important to note that in accordance with the above this kind of writing, used in the template, need this way {value} {newObj. Name.} (not understand), if you want to directly use {{name}}, so need to deconstruct the return in the setup

Import {toRefs} from "vue" export default {let obj = {name: 'zhang3 ', age: 18}; let newObj = toRefs(obj); SetTimeout (() => {newobj.name. console.log(obj, newObj); }, 2000); return { obj, ... newObj }; }Copy the code

{{name}} can be retrieved directly from the template.

The subtotal

1. Ref is a copy of metadata. Modifying reactive data will not affect the previous data, and the view will be updated

ToRef and toRefs are references to metadata. When reactive data is modified, the metadata also changes, but the view is not updated. ToRef modifies a property of the object, and toRefs modifies the entire object

3. ToRefs usage scenarios: If you want to associate reactive data with original data and update it synchronously without updating the view, you can use toRefs