原生js实现数据响应方法2.0
作用
实现类似vue的数据响应,改变其值去触发特定的回调
效果预览
代码
function createReactive(target,parent = "",callback = (longKey, newValue, oldValue) => {console.log(`Property ${longKey} changed from`, oldValue, 'to', newValue, '🤓');}) {if (typeof target !== 'object' || target === null) {return target;}const handler = {get(target, key) {const longKey = parent.length ? `${parent}.${key}` : keyconst value = target[key];if (typeof value === 'object' && value !== null) {console.log('get');return createReactive(value, `${longKey}`, callback);}return value;},set(target, key, newValue) {const longKey = parent.length ? `${parent}.${key}` : keyif (target[key] !== newValue) {console.log(`Property ${longKey} changed from`, target[key], 'to', newValue);callback(longKey, newValue, target[key])target[key] = newValue;return true;} else {return false}}};return new Proxy(target, handler);}// 使用示例const config = {name: 'John',age: 30,address: {city: 'New York',street: '123 Main St'}};const core = new CoreClass(config);// 修改普通属性core._config.age = 31;// 修改嵌套属性Object.assign(core._config, {address: {city: 'New York11',street: '123 Main St111'}})console.log(core);