利用Object.defineProperty实现Vue数据双向绑定

body部分很简单,一个输入框和一个展示的div

<div>
    <p>你好,<input id='nickName'></p>
    <div id="introduce"></div>
</div>

逻辑部分

    <script>
        var userInfo = {};
        var a = '';
        var inp = document.getElementById('nickName');
        var odiv = document.getElementById('introduce');
        Object.defineProperty(userInfo, "nickName", {
            get: function(){
                return inp.value;
            },
            set: function(nick){

            }
        });
        Object.defineProperty(userInfo, "introduce", {
            get: function(){

            },
            set: function(introduce){
                odiv.innerHTML = introduce;
            }
        })

        inp.addEventListener("keyup",function(){
            userInfo.introduce = userInfo.nickName;
        })

    </script>

效果是

 

posted @ 2018-10-17 13:54  若鱼灬  阅读(434)  评论(0编辑  收藏  举报