一篇文章带你搞懂Vue3语法中的ref和reactive的区别
ref响应式定义基本数据类型
在Vue3中,要实现数据的实时修改,我们可以使用ref,reactive来包裹我们定义的变量。其中ref可以定义基本数据类型以及对象类型,而reactive只能定义对象类型。
我们直接上代码来理解
使用ref定义基本数据类型。修改ref的值,使用.value
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
</div>
</template>
<script setup lang="ts" name="Person">
import {ref} from "vue";
//数据
let name = ref('张三')
let age = ref(18)
//方法
function changeName(){
name.value = 'Lisi'
}
function changeAge(){
age.value += 1
}
</script>
<style scoped>
.person{
background: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button{
margin: 0 5px;
}
</style>
上述代码,一开始定义了name,age为张三和18岁,定义了修改姓名以及年龄的按钮,并且绑定了方法。我们在script中定义方法的实现,由于是ref类型的,它的数值是在value中的,因此我们在修改ref的数值的时候要记得.value才可以
ref响应式定义对象类型
下面使用ref定义对象类型
<template>
<div class="person">
<h2>一辆{{car.brand}}车,价值{{car.price}}</h2>
<button @click="changeBrand">修改汽车的品牌</button>
<button @click="changePrice">修改汽车的价格</button>
<button @click="changeCar">修改汽车</button>
</div>
</template>
<script setup lang="ts" name="Person">
import {ref,reactive} from "vue";
let car = ref({brand:'奔驰',price:100})
function changeBrand(){
car.value.brand = "宝马"
}
function changePrice(){
car.value.price += 10
}
function changeCar(){
car.value = {brand:'奥迪',price:1}
}
</script>
<style scoped>
.person{
background: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
li{
font-size: 20px;
}
button{
margin: 5px;
}
</style>
上述代码中
let car = ref({brand:‘奔驰’,price:100})使用ref定义了一个brand是奔驰,price是100的对象。
由于car类型是ref,所以我们想获取或者修改car里面的数据的时候,要先.value,然后在.具体的数据
function changePrice(){
car.value.price += 10
}
car.vule拿到了car,car,value.price拿到了car的price属性,并且对它进行操作。如果不理解可以看下面的图
reactive响应式定义对象类型
使用reactive定义对象,在获取对象的数值的时候可以直接获取,不需要像ref一样先.value
<template>
<div class="person">
<h2>一辆{{car.brand}}车,价值{{car.price}}</h2>
<button @click="changeBrand">修改汽车的品牌</button>
<button @click="changePrice">修改汽车的价格</button>
<button @click="changeCar">修改汽车</button>
</div>
</template>
<script setup lang="ts" name="Person">
import {reactive} from "vue";
let car = reactive({brand:'奔驰',price:100})
function changeBrand(){
car.brand = "宝马"
}
function changePrice(){
car.price += 10
}
function changeCar(){
Object.assgin(car,{brand:'保时捷',price:1000})
}
</script>
<style scoped>
.person{
background: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
li{
font-size: 20px;
}
button{
margin: 5px;
}
</style>
上述代码使用reactive响应式定义数据时,我们修改数据中的一个数值,是可以的,但是如果要修改整个对象中的数据,那么我们要使用
function changeCar(){
Object.assgin(car,{brand:‘保时捷’,price:1000})
}
总结
ref其实里面是包含了reactive的。所以这也就是ref和reactive两个存在的意义。如下图