Home >Web Front-end >JS Tutorial >js code implements vue two-way data binding example

js code implements vue two-way data binding example

小云云
小云云Original
2018-02-24 14:20:192482browse

Two-way data binding interviews generally ask questions. First, you must understand the usage of accessor attributes and time relationships. Paste the code first and analyze it when you have time. I hope this article can help everyone.

Object.defineProperty(obj,propertyName,{                get:function(){
                    //读取obj对象的propertyName属性时执行
                },                set:function(currvalue){
                    //修改obj对象的propertyName属性时执行
                },
            });
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>js实现vue双向数据绑定 利用访问器属性</title></head><body>
    <input bind-value="value" type="text" placeholder="请输入..."  id="user-input">
    <p bind-text="value" id="show-input"></p>
    <script>
    var elems=[document.getElementById(&#39;user-input&#39;),document.getElementById(&#39;show-input&#39;)];        var data={
            initValue:&#39;&#39;,
        };        function define(obj,propertyName) {
            Object.defineProperty(obj,propertyName,{
                get:function(){
                    return this.initValue;
                },
                set:function(currvalue){
                    this.initValue=currvalue;                    //同步p
                    scan();
                },
            });
        }

        define(data,&#39;value&#39;);
        data.value=&#39;&#39;;
        scan();        //监听事件
        elems[0].addEventListener(&#39;keyup&#39;,function(e){
            var e=e||window.event;
            data.value=e.target.value;
        });        function scan(){
            for(var i=0;i<elems.length;i++){                var ele=elems[i];                for(var j=0;j<ele.attributes.length;j++){                    var attr=ele.attributes[j];                    if(attr.nodeName.indexOf(&#39;bind&#39;)>=0){
                        elems[1].innerHTML=data.value;
                        elems[0].setAttribute(&#39;current-values&#39;,data.value);
                    }
                }
            }
        }    </script></body></html>

Related recommendations:

Vue two-way data binding source code analysis

JS method to implement two-way data binding

Front-end js two-way data binding

The above is the detailed content of js code implements vue two-way data binding example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn