vue3中的reactive、readonly和shallowReactive使用詳解
1. reactive 與 readonly 使用
readonly:拷貝一份 proxy 對象將其設(shè)置為只讀。
使用 readonly 時, 變量里的屬性不可改變。

需要注意的是:
當(dāng)原本數(shù)據(jù)改變時,使用了 readonly 函數(shù)的值也會發(fā)生改變。
<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>
在這個例子中,修改響應(yīng)式對象中的 age 屬性, readonly 中的 age 屬性也會隨之更改。
2. shallowReactive
- 創(chuàng)建
淺層的響應(yīng)式對象 - 修改內(nèi)部屬性時,
只改變值,不更新視圖
在 Vue3 中,可以使用 shallowReactive 函數(shù)創(chuàng)建一個淺層響應(yīng)式對象。它接收一個普通對象作為參數(shù),返回一個淺層響應(yīng)式代理對象。這個代理對象只能處理對象的一級屬性,不能處理嵌套在對象中的屬性的響應(yīng)式更新。當(dāng)我們讀取代理對象的屬性時,會觸發(fā)依賴收集;當(dāng)我們修改代理對象的屬性時,會觸發(fā)相應(yīng)的依賴更新。在調(diào)用 shallowReactive 函數(shù)時, Vue3 會使用 Proxy 對象對傳入的對象進行代理,從而實現(xiàn)淺層響應(yīng)式特性。
<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 的值變?yōu)?7

點擊 test2 后:視圖沒有發(fā)生改變,控制臺如下

到此這篇關(guān)于vue3中的reactive、readonly和shallowReactive的文章就介紹到這了,更多相關(guān)vue3 reactive、readonly和shallowReactive內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue?+?element-ui?季度選擇器組件?el-quarter-picker示例詳解
本文介紹如何在Vue項目中使用基于Element-UI的季度選擇器組件ElQuarterPicker,通過引用并調(diào)用ElQuarterPicker.vue組件來實現(xiàn)季度選擇功能,感興趣的朋友跟隨小編一起看看吧2024-09-09
vue+Element實現(xiàn)搜索關(guān)鍵字高亮功能
這篇文章主要為大家詳細介紹了vue+Element實現(xiàn)搜索關(guān)鍵字高亮功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
ant-design-vue 實現(xiàn)表格內(nèi)部字段驗證功能
這篇文章主要介紹了ant-design-vue 實現(xiàn)表格內(nèi)部字段驗證功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
關(guān)于vue3+echart5?遇到的坑?Cannot?read?properties?of?undefine
這篇文章主要介紹了vue3+echart5?遇到的坑?Cannot?read?properties?of?undefined?(reading?'type'),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

