模拟Vue双向绑定

 <!--模拟Vue-->
    <script>
        window.onload = function(){
            Binding("ins","boxs");
        }

        function Binding(ins,boxs){
            // 创建数据对象
            window.data = {};
            // 创建数据键值对
            let _name = "";
            let my_input = document.getElementById('ins');
            let desc = document.getElementById("boxs");

            Object.defineProperty(window.data, "name", {
                // 返回数据
                get: function(){
                    return _name;
                },
                // 设置数据
                set: function(value){
                    _name = value;
                    // 将新数据添加到input和div元素内
                    my_input.value = value;
                    desc.innerHTML = value;

                }
            });
            // 获取input按钮, 并为其绑定事件
            my_input.addEventListener('input', function (ev) {
                new_data = ev.target.value;
                console.log("当前输入框内的数据为:",new_data);
                // 将框内的数据赋值给, data
                window.data.name = new_data
            })
        }
    </script>

猜你喜欢

转载自blog.csdn.net/Byte_Dance/article/details/85095507