In Vue3, Object. Defineproperty is no longer used for attribute listening in Vue2. Instead, the Proxy mode is used with Reflect listener. This paper uses several commonly used handler processor methods, add, delete, change and check, and achieve a simple read-only function.
Const readonlyHandler = {get(target, prop) {return reflect.get (target, prop)}, Set (target, prop, val) {console.warn(' cannot set data ') return true}, deleteProperty(target, prop) {console.warn(' can only read data, Function shallowReadonly(target) {function shallowReadonly(target) {// Determine whether target is an object if (target &&) Typeof target === 'object') {return new Proxy(target, readonlyHandler)} Function readOnly (target) {if (target && typeof target === If (array.isarray (target)) {target.foreach ((val, I) => {// array recursive processing target[I] = readonly(val)})} else {// Object traversal recursive object.keys (target).foreach ((key) => {target[key] = Readonly (target[key])})} return new Proxy(target, readonlyHandler)}Copy the code
1. Test shallowReadonly:
Const user = shallowReadonly({name: '小 小 ', age: 18, skill: ['eat', 'drink', 'sleep']}) user.name = 'red' delete user.name user. Skill [0] = 'study' console.log(user.skill)Copy the code
2. Test readonly
Results:
Const user2 = Readonly ({name: '小 Ming ', age: 18, skill: ['eat', 'drink', 'sleep']}) user2.name = 'small red' delete user2.name user2.name user2.log (user2.skill)Copy the code