js如何实时监听变量的值发生变化?
网友回复
在 JavaScript 中有几种方法可以监听变量的变化。我列举几种常用的方法:
使用 Vue 的 watch(如果在 Vue 项目中):
new Vue({ data: { someValue: '' }, watch: { // 基础监听 someValue(newVal, oldVal) { console.log('值变化:', oldVal, '->', newVal); }, // 深度监听对象 someObject: { handler(newVal, oldVal) { console.log('对象变化:', oldVal, '->', newVal); }, deep: true }, // 立即执行 someData: { handler(newVal, oldVal) { console.log('数据变化:', oldVal, '->', newVal); }, immediate: true } } });
使用 Object.defineProperty(Vue2 的实现原理):
let value = ''; let oldValue = value; Object.defineProperty(window, 'watchedValue', { get() { return value; }, set(newValue) { oldValue = value; value = newValue; // 值变化时的回调 onValueChange(value, oldValue); } }); function onValueChange(newValue, oldValue) { console.log('值变化:', oldValue, '->', newValue); } // 使用 watchedValue = 'new value'; // 会触发 onValueChange
使用 Proxy(Vue3 的实现原理):
const data = { value: '' }; const proxy = new Proxy(data, { get(target, property) { return target[property]; }, set(target, property, value) { const oldValue = target[property]; target[property] = value; // 值变化时的回调 onValueChange(property, value, oldValue); return true; } }); ...
点击查看剩余70%