Preface: vue3.0 needs to use Proxy to implement two-way binding, so let’s try the implementation method first.
1 Implementation
It turns out that the implementation of vue2 uses the monitoring set, but the array is directly subscripted and the array is set to monitor the value.
function observe(data) { if (!data || typeof data !== 'object') { return; } // Take out all attributes to traverse (data).forEach(function(key) { defineReactive(data, key, data[key]); }); }; function defineReactive(data, key, val) { observe(val); // Listen to subproperties (data, key, { enumerable: true, // Enumerable configurable: false, // You can no longer rewrite defineProperty get: function() { return val; }, set: function(newVal) { ('----------------------------------------------------) val = newVal; } }); }
2 Implementation using Proxy
The principle of using Proxy is to new a Proxy object and proxy your data value. One thing to note is that for array method operations, two assignment operations will be generated, one is to add value and the other is to change its length value. For array subscripts that cannot be listened to, Proxy can listen to it.
function observe(data) { if (!data || typeof data !== 'object') { return; } // Take out all attributes to traverse (data).forEach(function(_k) { // Proxy does not allow binding to non-objects if (data[_k] && typeof data[_k] === 'object') { data[_k] = defineReactive(data[_k]); } }); } function defineReactive(data) { return new Proxy(data, { set(target, key, value, proxy) { // When performing array operations, set will be performed twice. Once the data is changed, the length will be changed, and the value of data will remain unchanged. Therefore, no more messages should be distributed if ( (data) === "[object Array]" && key === "length" ) { (target, key, value, proxy); return true; } observe(data); (target, key, value, proxy); ('----------------------------------------------------) return true; } });
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.