The difference between proxy and defineProperty

A mutable concept

        Before that, we first solve themutable

        mutable represents an object of mutable type. Provides operations that can change its internal data value, and its internal value can be changed again.

        Vue uses variable data sources as the core concept to realize the entire UI change update

mutable (variable type) immutable (immutable type)
advantage Reduce the number of data copies and achieve higher efficiency The internal data is immutable, which makes it safer and can be used as a multi-threaded shared object, without having to consider synchronization issues
shortcoming Internal data is variable, leading to greater risk Internal data is immutable, and frequent modifications will generate a large number of temporary copies to waste space

        The simplest way to put it is: initialize the data to generate the page, directly modify the source data to trigger the update, and the page is re-rendered

Two defineProperty

        When using vue2, we often encounter a problem. Adding new object properties obj.a = 1will not be hijacked by vue2, and we must use the methods provided by vue2 $setto update.

         Because when we add a property to object a, although a new property is successfully generated on the corresponding object, vue2 hijacks data through the setter and getter of defineProperty, and the newly added data is not hijacked. So no matter how updated, the page will still not be re-rendered

        (The reason for this is that defineProperty can only hijack one of the properties of the current object)

const a = {
    b: 1,
};
Object.defineProperty(a, 'b', {
    set: function() {},
    get: function() {},
});

three proxy

        In vue3, using proxy for data proxy does not have this concern at all

        Proxy for data proxy can respond to new attributes. When a new attribute is added, it can respond to get and proxy the current object.

const p = new Proxy({
    a: 1,
    b: 2,
}, {
    get: function(obj, value) {
        console.log('get', obj, value);
        return Reflect.get(obj, value);
    },
    set: function(obj, prop, value) {
        console.log('set', obj, prop, value);
        return Reflect.set(obj, prop, value);
    },
})

Guess you like

Origin blog.csdn.net/weixin_46669844/article/details/128474170