Vue.js -Handwritten implementation of a simple two-way data binding

Time:2020-12-10

Two way data binding is almost the most we hear about in Vue. V-model is our most common bidirectional data binding instruction. So how does it work? Let’s write it together.

<body>
    <input type='text'>
    <span class='ppp'></span>
</body>

<script>
    let obj = {};
    let temp;
    
    let ipt = document.querySelector('input');
    ipt.oninput = function(){
        obj.a = ipt.value;
    }
    
    //Gets the focus and the user modifies the value
    Object.defineProperty(obj,'a',{
        get:function(){
            return temp;
        },
        set:function(val){
            temp = val;
            ipt.value = val;
            document.querySelector('ppp').innerHTML = val;
        }
    })
    
    //When the a attribute in obj changes, the value of input changes
    //When the value of input changes, the a attribute of obj changes
</script>

Recommended Today

What other languages does the JVM support

In order to make Java language have good cross platform ability, Java provides a kind of intermediate code — bytecode, which can be used on all platforms. With bytecode, no matter which platform (such as windows, Linux, etc.), as long as the virtual machine is installed, you can directly run bytecode. Similarly, bytecode also decouples […]