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

Choose react or angular 2

Original addressChoosing between React vs. Angular 2The following is the translation of this article, which can be used at your choiceReactperhapsAngular2We need to help when we need to. React has become a cool representative in 2015, but angular.js has changed from a front-end framework that people love to a terrible devil (and not so terrible…) […]