利用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 對於普通數據,重新賦值,會報錯, 對於引用數據的數據修改,他是正常修改的,因為引用數據的內存地址沒有發生改變