Reactive全家桶

reactive的作用也是创建一个响应式对象,reactive与ref的区别是reactive只接收引用类型(Object,Array,Map等),且使用时不用加.value。而ref接受任何类型,且使用时需要加.value。reactive的使用场景一般为为form表单进行数据双向绑定。

由于reactive是一个proxy对象,所以不能直接用对象或者数组对reactive进行赋值,这样会让reactive失去响应性。

readonly

readonly能够将reactive变成只读的

vue
123456
<script setup lang="ts">
import { reactive, readonly } from 'vue';
const Cain = reactive({name: "Cain"})
const read = readonly(Cain)
//这样read就是Cain的只读版本了,是不能直接修改read里面的属性的,但是能够通过修改Cain的属性来间接修改read属性
</script>

shallowReactive

与shallowRef相同,能将reactive变成浅层次的响应,根本原因还是因为没有触发视图的更新

vue
1234567891011121314151617181920
<template>
  <button @click="change">修改</button>
  <h1>{{ shallowCain.first.name }}</h1>
</template>

<script setup lang="ts">
import { reactive, readonly, shallowReactive } from "vue";
const shallowCain = shallowReactive({
  first: {
    name: "Cain",
  },
});
const Cain = reactive({ name: "Cain" });
const read = readonly(Cain);
const change = () => {
  //这样修改是不可以的,因为shallowReactive只到第一层即first
  shallowCain.first.name = "我被修改了";
};
</script>

同样,shallowReactive也具有与shallowRef相同的特性,即与reactive写到一起的时候,也会引起shallowReactive的更新