In the course of studying V3, I found that these three are very similar, but very different, so keep a note

1. Use of ref

Ref takes a raw value and returns a responsive object that has a value property, the value of which is the original value passed

    setup(){
       	let msg = { name: 'zs'.age: 16 }
       	let msg1 = ref(msg.name)       
       	console.log(msg1.value)   // zs
    	function change1() {
          msg1.value = 'ls'
          console.log(msg, msg1.value) // {name: "zs", age: 16} ls
    	}
    	change1()
    	return { msg1,change1 }
    }
Copy the code

Conclusion: ref is a copy relationship made. If the value of msg1 is modified, the object MSG will not be affected and the view will change

2. Use of toRef

ToRef is used to extract an attribute from a responsive object and wrap the attribute into a REF object, linking it to the original object

    setup(){
    	let msg = { name: 'zs'.age: 16 }
        let msg2 = toRef(msg, 'name')
        console.log(msg2.value)	// zs
        function change2() {
            msg2.value = 'ww'
            console.log(msg, msg2.value) // {name: "ww", age: 16} ww
        }
        change2()
        return { msg2,change2 }
    }
Copy the code

Conclusion: toRef is a kind of reference relationship made, changing the value of MSg2 will affect the object MSG, but the view will not change

3. Use of toRefs

ToRefs is used to convert reactive objects into normal objects, wrapping each attribute in the object as a Ref object

setup(){
    let msg = { name: 'zs'.age: 16 }
    let msg3 = toRefs(msg)
    console.log(msg) // {name:ref, age:ref} ref represents the ref object
    function change3() {
      msg3.name.value = 'zl'
      msg3.age.value = 20
      console.log(msg, msg3) // {name: "zl", age: 20} { name:ref, age:ref }
    }
    change3()
    return { msg3, change3 }
}
Copy the code

Conclusion: toRefs is an upgraded version of toRef, except that toRefs transforms reactive objects, and the rest of the features are the same as toRef

4. Summary of the three

  1. View level: When ref data is modified, the view will also change, and when toRef data and toRefs data are modified, the view will not change
  2. Data level: When ref data is modified, the original data will not be changed; when toRef data and toRefs data are modified, the original data will be changed
  3. Parameter level: toRef needs to pass two parameters, the first parameter is the object to be converted, the second parameter is the attribute name in the object, toRefs only needs to pass one parameter, is the object to be converted