接受一个对象(不管是响应式还是普通的)或者是一个ref,返回的是一个原值的只读代理。
<template>
<n-el class="h-400 w-full flex flex-col justify-center items-center">
<n-el>{{ data }}</n-el>
<n-el>{{ readonlyData }}</n-el>
<n-button @click="handleAddData">增加data</n-button>
<n-button class="!mt-2" @click="handleAddReadonlyData">增加readonlyData</n-button>
</n-el>
</template>
<script setup lang="ts">
import { readonly, ref } from 'vue'
const data = ref(100)
const readonlyData = readonly(data)
const handleAddData = () => {
data.value++
}
const handleAddReadonlyData = () => {
readonlyData.value++
}
</script>
编辑器提示
readonly()
的浅层作用形式
<template>
<n-el class="h-400 w-full flex flex-col justify-center items-center">
<n-el>{{ obj.a }}</n-el>
<n-el>{{ obj.b.res }}</n-el>
<n-el>{{ obj.b.c.res }}</n-el>
<n-el>------------------------</n-el>
<n-el>{{ readonlyObj.a }}</n-el>
<n-el>{{ readonlyObj.b.res }}</n-el>
<n-el>{{ readonlyObj.b.c.res }}</n-el>
<n-button class="!mt-2" @click="handleAddObj">增加obj</n-button>
<n-button class="!mt-2" @click="handleAddReadonlyObj">增加readonlyObj</n-button>
</n-el>
</template>
<script setup lang="ts">
import { reactive, shallowReadonly } from 'vue'
const obj = reactive({
a: 1,
b: {
res: 2,
c: {
res: 3,
},
},
})
const readonlyObj = shallowReadonly(obj)
const handleAddObj = () => {
obj.a = 100
obj.b.res = 200
obj.b.c.res = 300
}
const handleAddReadonlyObj = () => {
readonlyObj.a = 100
readonlyObj.b.res = 200
readonlyObj.b.c.res = 300
}
</script>
增加obj
增加readonlyObj