一、Reactive?
- reactive的参数呢一般是
对象
或者数组
,能够将复杂的数据
类型变为响应式数据
。 - reactive的响应式是深层次的,底层本质就是将传入的数据转换为
Proxy
对象
使用reactive来定义数据
<template>
<h2>{{obj}}</h2>
<h2>{{obj.age}}</h2>
<button @click="editAge">操作age</button>
</template>
<script>
import { ref, reactive } from "vue";
export default {
setup() {
// reactive定义复杂数据类型
const obj = reactive({
name:'复杂数据',
age:20
});
// 操作修改age
const editAge = ()=>{
obj.age ++
}
return {
obj,
editAge
};
},
};
</script>
<style>
</style>
二、Proxy和defineProperty
reactive方法内部是利用ES6的Proxy API来实现的,这里与Vue2中的defineProperty方法有本质的区别。
- defineProperty只能单一地监听已有属性的修改或者变化,无法检测到对象属性的新增或删除,而Proxy可以轻松实现
- defineProperty无法监听属性值是数组类型的变化,而Proxy可以轻松实现
二、ref
- ref的参数一般是
基本数据类型
,也可以是对象类型 - 如果参数是对象类型,其实底层的本质还是reactive,系统就会自动将ref转换为reactive
- 我们如果去访问ref定义的值,那么就使用
.value
的属性去访问定义的数据 - ref的底层原理同reactive一样,都是Proxy
ref的使用
<template>
<p>{{ name }}</p>
<h1>{{ num }}</h1>
<button @click="editNum">修改num</button>
</template>
<script>
import { ref, reactive } from "vue";
export default {
setup() {
// ref定义简单数据类型
const name = ref("ref简单数据类型");
const num = ref(0);
// 修改数据(基本数据类型用.value)
const editNum = () => {
num.value ++;
};
return {
name,
num,
editNum,
};
},
};
</script>
<style>
</style>
总结
- reactive参数一般接收
对象
或者数组
,是深层次的响应式 - ref的参数一般接收
简单数据类型
为参数,本质上会转变为reactive的方法 - 在JS中我们如果去对数据进行操作,在
ref
定义的数据中,使用变量.value
;访问reactive不需要 - 响应式的底层原理都是proxy