js深层双向绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <input type="text" id="text">
    <p id="show"></p>
<script>
    //监听不了深层该改变
    // var obj = {
    //     txt:''
    // }
    // Object.defineProperty(obj,'txt',{
    //     get:function(){
    //         return obj
    //     },
    //     set:function(newValue){
    //         document.getElementById('text').value = newValue;
    //         document.getElementById('show').innerHTML = newValue
    //     }
    // })
    // document.addEventListener('keyup',function(e){
    //     obj.txt = e.target.value
    // })

    var obj = {
        name:"张飞",
        age:18,
        info:{
            address:"陕西西安",
        }
    }
    function defineReactive(obj,target,value){
        observer(value)
        Object.defineProperty(obj,target,{
            get:function(){
                return value
            },
            set:function(newValue){
                value = newValue
                document.getElementById('text').value = newValue;
                document.getElementById('show').innerHTML = newValue
            }
        })
    }
    function observer(obj){
        if (typeof obj !== 'object' || obj === null) {
            // 不是对象或数组
            return obj
        }
        // 重新定义各个属性(for in 也可以遍历数组)
        for (var key in obj) {
            defineReactive(obj, key,obj[key])
        }
    }
    observer(obj);
    document.addEventListener('keyup',function(e){
        obj.info.address = e.target.value
    })
</script>
</body>
</html>

你可能感兴趣的:(js,vue)