是不是大家对于vue3中refi和reactive的两种响应式数据声明方式有些懵,今天我们就来讲下他们的区别。
在Vue 3中,ref 和 reactive 是两种主要的响应式数据声明方式,它们都是Vue 3的Composition API的一部分。
1. ref
ref用来定义:基本类型数据、对象类型数据;ref会返回一个可变的响应式引用对象,其.value属性指向内部值。
代码示例
<template>
<div>
<h1>{{ message }}</h1>
<button @click="greet">Greet</button>
</div>
<h4>文章名称:{{article.name}}</h4>
<h4>文章内容:{{article.content}}</h4>
<button @click="changeName">修改标题</button>
</template>
<script setup>
import { ref } from 'vue';
// 使用ref来创建响应式数据
const message = ref('Hello, Vue 3 with Composition API!');
// 定义一个函数,该函数可以直接访问和修改message
const greet = () => {
alert('Hello from Vue 3 with Composition API!');
message.value = 'Greeting updated with Composition API!';
};
//定义对象类型
let article = ref({name:"学习vue3的第一课",content:"vue3是一个前端框架"})
function changeName(){
article.value.name="学习vue3的第二课"
}
</script>
以上代码中我们看到了使用ref既可以定义基本类型的响应式数据,又可定义对象类型的响应式数据。当修改数据的值的时候都需要使用.value去修改。
2. reactive
reactive 用于创建对象的响应式引用。当你需要让整个对象(及其嵌套对象)都是响应式时,应该使用reactive。与ref不同,reactive返回的对象本身是响应式的,你不需要通过.value来访问它。
代码示例
<template>
<div>
<h1>{{ message }}</h1>
<button @click="greet">Greet</button>
</div>
<h4>文章名称:{{article.name}}</h4>
<h4>文章内容:{{article.content}}</h4>
<button @click="changeName">修改标题</button>
</template>
<script setup>
import { ref,reactive } from 'vue';
// 使用ref来创建响应式数据
const message = ref('Hello, Vue 3 with Composition API!');
// 定义一个函数,该函数可以直接访问和修改message
const greet = () => {
alert('Hello from Vue 3 with Composition API!');
message.value = 'Greeting updated with Composition API!';
};
let article = reactive({name:"学习vue3的第一课",content:"vue3是一个前端框架"})
function changeName(){
article.name="学习vue3的第二课"
}
</script>
使用reactive的时候可以不需要使用.value。
还有一点需要注意的是,当使用reactive的时候,需要重新分配一个完整对象时。应该使用Object.assign去整体替换
Object.assign(article, { name: '学习vue3的第二课', content: "vue3很好用" })
这种当后端传过来的数据量比较大时,可以整体替换。
那既然ref和reactive都可定义响应式数据,那我们平时开发时应该怎么使用呢,接下来给了几点基本原则。
如果是基本类型的响应式数据,使用ref。
如果是响应式对象,层级不深,ref、reactive都可以。
如果是响应式对象,且层级较深,推荐使用reactive。
本文暂时没有评论,来添加一个吧(●'◡'●)