JS 双向数据绑定、单项数据绑定

简单的双向数据绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="text" id="aa"/>
<span id="bb" style="border: 2px solid orange;margin-left: 20px;">{{hello}}</span>
<br>
<br>
<input type="text" id="cc"/>

<script>
    // 双向数据绑定的原理:属性拦截
    // 属性拦截实现方式 : 使用Object.defineProperty()将对象的属性变成访问器属性。

    var obj = {};
    Object.defineProperty(obj, 'hello', {
        enumerable: true,
        configurable: true,
        get: function () { // 拿到最新的值
            return document.getElementById('aa').value;
        },
        set: function (val) { // 设置最新的值
            document.getElementById('bb').innerHTML = obj.hello;
            document.getElementById('cc').value = obj.hello;
        }
    });
    Object.defineProperty(obj, 'hello2', {
        enumerable: true,
        configurable: true,
        get: function () {
            return document.getElementById('cc').value;
        },
        set: function (val) {
            document.getElementById('aa').value = obj.hello2;
            document.getElementById('bb').innerHTML = obj.hello2;
        }
    });
    document.getElementById('aa').onkeyup = function () {
        obj.hello = this.value;
    };
    document.getElementById('cc').onkeyup = function () {
        obj.hello2 = this.value;
    };
    obj.hello = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
    obj.hello2 = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
</script>
</body>
</html>

单项数据绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="text" id="aa"/>
<span id="bb" style="border: 2px solid orange;margin-left: 20px;">{{hello}}</span>

<script>
    // 双向数据绑定的原理:属性拦截
    // 属性拦截实现方式 : 使用Object.defineProperty()将对象的属性变成访问器属性。

    var obj = {};
    Object.defineProperty(obj, 'hello', {
        enumerable: true,
        configurable: true,
        get: function () {
            return document.getElementById('aa').value;
        },
        set: function (val) {
            document.getElementById('bb').innerHTML = obj.hello;
        }
    });

    document.getElementById('aa').onkeyup = function () {
        obj.hello = this.value;
    };

    obj.hello = ""; //属性名必须设置为空,否则在使用插值表达式的时候直接会把插值表达式显示出来
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/haohaogan/p/15700295.html