The difference between vue3 ref and reactive is the same as

Let me talk about the difference first. If you use the data defined by ref directly in the template, you don’t need to add .value, because the value defined by ref in the template has been exposed, but you must add the defined object name if you use reacative definition, such as If const data=reactive({name:"cat"}) is defined, then data.cat must be used in the template. This is the first difference.

The second is that reactive generally stores arrays or objects, which can turn complex types into responsive data, and ref generally stores basic data, and the responsiveness of reactive is deep.

The same point: Both of them are responsive through the proxy proxy of Es6, and ref is essentially a child of reactive.

Here are some examples to better understand what I'm talking about

<template>
	<h1>{
   
   { name }}</h1>
</template>

<script setup> 
import { ref} from 'vue'
const name=ref("cat")
</script>
//在模板中直接使用即可,vue会自动帮我们加上.value
如果ref的value接收的是一个对象,那么vue会直接将ref转化为reactive
<template>
	<h1>{
   
   { data.name }}</h1>
</template>

<script setup>
import { ref,reactive} from 'vue'
const data=reactive({
        name:"cat"
})
</script>
//使用reactive定义变量一定要加上变量名,类似于对象使用点表明对象

So how to judge whether the data is ref or reactive type? Vue provides us with the isRef / isReactive method

<template>
  <div>
    <p>{
   
   {data.name}}</p>
  </div>
</template>
 
<script>
 
  import {reactive,ref} from 'vue';
    let data= reactive({name: "cat"});
    function Fn() {
       console.log(isRef(data.name)); //false
       console.log(isReactive(data.name));  //true
    }
}
</script>

Guess you like

Origin blog.csdn.net/qq_45662523/article/details/126577717