Vue.js adopts the data hijacking + publish/subscribe mode. It hijacks the setter/getter of each attribute through Object.defineProperty() to publish messages to subscribers (Wacther) when data changes and trigger corresponding listening callbacks.

Implement a simple bidirectional binding

<div id="app">
    <input type="text" id="txt">
    <p id="show-txt"></p>
</div>
<script>
    var obj = {}
    Object.defineProperty(obj,'txt',{
        get:function(){
            return obj
        },
        set:function(newVal){
            document.getElementById('txt').value = newVal
            document.getElementById('show-txt').innerHtml = newVal
        }
    })
    document.addEventListener('keyup',function(e){
        obj.txt = e.target.value
    })
</script>
Copy the code

Vue internally converts every read and write of data in a data Object into a getter/setter by intercepting the Object. DefineProperty method attribute, notifying the view of updates when data changes.

Object change detection

Object.defineProperty(obj,prop,descriptor)

  • Obj: Object for which attributes are to be defined
  • Prop: Name of the property to define live modification
  • Descriptor: Attribute descriptor to define live modifications
Object. DefineProperty (obj,key,{enumerable:true, different :true, get(){console.log(' ${key} property is modified '); }, set(newVal){if(val === newVal){return} console.log(' ${key} property changed '); val = newVal } })Copy the code

The object.defineProperty () method directly defines a new property on an Object, or modifies an Object’s desired property, and returns the Object.