readonly函数
- readonly 接收收一个对象或一个响应式对象
- readonly 返回的对象的代理,该对象的属性是只读的(深层)
<template>
<div>当前求和为 {{sum}}</div>
<div>{{name}} --- {{age}} --- {{job.j1.salary}}</div>
<div>
<button @click="name+='~'">改名</button>
<button @click="age++">增加年龄</button>
<button @click="job.j1.salary+=10">增加工资</button>
</div>
</template>
<script>
import {reactive, ref, toRefs, readonly, } from 'vue'
export default {
setup() {
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 3000
}
}
})
person = readonly(person) // 现在person里面的所有属性都是只读的
let sum = ref(0)
return {
sum,
...toRefs(person)
}
}
}
</script>
shallowReadonly函数
<template>
<div>当前求和为 {{sum}}</div>
<div>{{name}} --- {{age}} --- {{job.j1.salary}}</div>
<div>
<button @click="name+='~'">改名</button>
<button @click="age++">增加年龄</button>
<button @click="job.j1.salary+=10">增加工资</button>
</div>
</template>
<script>
import {reactive, ref, toRefs, shallowReadonly} from 'vue'
export default {
setup() {
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 3000
}
}
})
person = shallowReadonly(person) // 现在person对象里面的第一层属性是只读的
let sum = ref(0)
return {
sum,
...toRefs(person)
}
}
}
</script>
- shallowReadonly 返回的对象,仅第一层的属性是只读的