readonly
接收一个 ref
或者 reactive
包装对象,返回一个只读的响应式对象。
实例:
<template>
<div>
<p>count的值为{{ count }}</p>
<a-button @click="countAdd">count++</a-button>
<p>res{{ res }}</p>
<a-button @click="resAdd">res++</a-button>
<hr />
<h2>名字:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>地址:{{ other.address.country }}</h2>
</div>
</template>
<script lang="ts">
import { reactive, ref, toRefs, readonly } from 'vue'
export default {
name: 'example',
setup() {
let count = ref(4)
let student = reactive({
name: 'xiaoming',
age: 18,
other: {
address: {
country: 'test',
},
},
})
let res = readonly(count)
let obj = readonly(student)
function countAdd() {
count.value++
}
function resAdd() {
res.value++
}
return {
count,
res,
...toRefs(obj),
countAdd,
resAdd,
}
},
}
</script>
编译器会报错:
可以看到,res
是不可修改的,因为readonly
特性是深度只读数据。
但是,原始数据修改了之后,其值会跟着变,如下图: