1. reactive 与 readonly 使用
readonly:拷贝一份 proxy 对象将其设置为只读。
使用 readonly 时, 变量里的属性不可改变。

需要注意的是:
当原本数据改变时,使用了 readonly 函数的值也会发生改变。
<template>
<div>
<form>
<input v-model="obj.name" type="text" />
<br />
<input v-model="obj.age" type="text" />
<br />
<button @click.prevent="submit">提交</button>
</form>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, readonly, shallowreactive } from 'vue'
const obj = reactive({
name: '张三',
age: 23
})
const copy = readonly(obj)
const submit = () => {
obj.age++
console.log(copy)
}
</script>
在这个例子中,修改响应式对象中的 age 属性, readonly 中的 age 属性也会随之更改。
2. shallowreactive
- 创建
浅层的响应式对象 - 修改内部属性时,
只改变值,不更新视图
在 vue3 中,可以使用 shallowreactive 函数创建一个浅层响应式对象。它接收一个普通对象作为参数,返回一个浅层响应式代理对象。这个代理对象只能处理对象的一级属性,不能处理嵌套在对象中的属性的响应式更新。当我们读取代理对象的属性时,会触发依赖收集;当我们修改代理对象的属性时,会触发相应的依赖更新。在调用 shallowreactive 函数时, vue3 会使用 proxy 对象对传入的对象进行代理,从而实现浅层响应式特性。
<template>
<div>{{ state }}</div>
<br />
<button @click="change1">test1</button>
<br />
<button @click="change2">test2</button>
</template>
<script setup lang="ts">
import { ref, reactive, readonly, shallowreactive } from 'vue'
const state = shallowreactive({
a: 1,
first: {
b: 2,
second: {
c: 3
}
}
})
const change1 = () => {
state.a = 7
}
const change2 = () => {
state.first.b = 8
state.first.second.c = 9
console.log(state)
}
</script>点击 test1 后: state.a 的值变为 7

点击 test2 后:视图没有发生改变,控制台如下

到此这篇关于vue3中的reactive、readonly和shallowreactive的文章就介绍到这了,更多相关vue3 reactive、readonly和shallowreactive内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论