🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
* readonly 函数 * 深度只读数据。 * 获取一个对象 (响应式或纯对象) 或 ref 并返回原始代理的只读代理。 * 只读代理是深层的:访问的任何嵌套 property 也是只读的。 * shallowReadonly 函数 * 浅只读数据,只能使对象的第一层是只读的,第2层及更深层不是只读的。 * 创建一个代理,使其自身的 property 为只读,但不执行嵌套对象的深度只读转换。 * 应用场景: * 在某些特定情况下,我们可能不希望对数据进行更新的操作,那就可以包装生成一个只读代理对象来读取数据,而不能修改或删除。 ```html <template> <!-- 4. 模板引用state --> <h3>state: {{ state }}</h3> <hr /> <button @click="update">更新</button> </template> <script lang="ts"> import { defineComponent, reactive, readonly, shallowReadonly } from "vue"; export default defineComponent({ setup() { //1. 创建一个响应式的对象 const state = reactive({ name: "张三", age: 20, car: { name: "奔驰", price: 100, }, }); //2. 将state分别传入readonly和shallowReadonly //const readonely01 = readonly(state) const shallowReadonly01 = shallowReadonly(state); //3. 更新情况 const update = () => { //深度只读,不能更新 //readonely01.age += 10 //readonely01.car.price += 10 //第1层的不能更改,更改失败 //shallowReadonly01.age += 10 //浅度只读,可以更改第2层及其更深层的数据 shallowReadonly01.car.price += 100; }; return { state, update, }; }, }); </script> ``` ![](https://img.kancloud.cn/44/12/44129915d80b7850ec33b664e9e7bcd8_1344x145.gif)