利用readonly封装数据,递归只读
<template>
<div>
<p>{{state.name}}</p>
<p>{{state.attr.age}}</p>
<p>{{state.attr.height}}</p>
<button @click="myFn">按钮</button>
</div>
</template>
<script>
import {readonly} from 'vue'
export default {
name: 'App',
setup() {
// readonly:用于创建一个只读的数据, 并且是递归只读
let state = readonly({name:'lnj', attr:{age:18, height: 1.88}});
function myFn() {
state.name = '知播渔';
state.attr.age = 666;
state.attr.height = 1.66;
console.log(state); //数据并没有变化
}
return {state, myFn};
}
}
</script>
<style>
</style>
打印情况

点击按钮,尽管重新赋值了数据,但是并没有更改数据,所以只能是只读的,并且是递归只读,层级深的数据也是没有变化。而且页面并没有跟新
利用shallowReadonly封装数据,非递归只读
<template>
<div>
<p>{{state.name}}</p>
<p>{{state.attr.age}}</p>
<p>{{state.attr.height}}</p>
<button @click="myFn">按钮</button>
</div>
</template>
<script>
import {shallowReadonly} from 'vue'
export default {
name: 'App',
setup() {
// readonly:用于创建一个只读的数据, 并且是递归只读
let state = shallowReadonly({name:'lnj', attr:{age:18, height: 1.88}});
function myFn() {
state.name = '知播渔';
state.attr.age = 666;
state.attr.height = 1.66;
console.log(state);
}
return {state, myFn};
}
}
</script>
<style>
</style>
打印效果

此时,只对最外层数据name属性有只读效果,内层的数据都改变了,非递归只读,页面同样也是未发生更新
关于isReadeonly,以及readonly和const区别
<template>
<div>
<p>{{state.name}}</p>
<p>{{state.attr.age}}</p>
<p>{{state.attr.height}}</p>
<button @click="myFn">按钮</button>
</div>
</template>
<script>
/*
1.readonly
- 只读数据
2.readonly和const
- const 赋值保护
- readonly 递归保护
3.isReadonly
- 判断是否是readonly
4.shallowReadonly
- 非递归保护
* */
import {readonly, isReadonly, shallowReadonly} from 'vue'
export default {
name: 'App',
setup() {
// readonly:用于创建一个只读的数据, 并且是递归只读
let state = readonly({name:'lnj', attr:{age:18, height: 1.88}});
// shallowReadonly: 用于创建一个只读的数据, 但是不是递归只读的
// let state = shallowReadonly({name:'lnj', attr:{age:18, height: 1.88}});
// const和readonly区别:
// const: 赋值保护, 不能给变量重新赋值,
// readonly: 属性保护, 不能给属性重新赋值
// const value = 123;
const value = {name:'zs', age:123};
function myFn() {
state.name = '知播渔';
state.attr.age = 666;
state.attr.height = 1.66;
console.log(state);
console.log(isReadonly(state)); //true
// value = 456;
// console.log(value);
value.name = 'ls';
value.age = 456;
console.log(value);
}
return {state, myFn};
}
}
</script>
<style>
</style>
注,对于readonly和shallowreadonly封装的数据,重新修改数据,它的isReadonly都是true
const 对于普通数据,重新赋值,会报错, 对于引用数据的数据修改,他是正常修改的,因为引用数据的内存地址没有发生改变