js实现双向数据绑定,vue v-model原理

<!DOCTYPE html>
<html lang="zh">

<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></title>
</head>

<body>
    <div>
        <div id="content"></div>
        <input type="text" name="" id="inputName">
    </div>
</body>
<script>
    let obj = {
        name: ''
    }

    let newObj = JSON.parse(JSON.stringify(obj))

    Object.defineProperty(obj,'name',{
        get() {
            return newObj.name
        },
        set(val) {
            if(val === newObj.name) return
            newObj.name = val
            observer()
        }
    })

    function observer() {
        content.innerHTML = newObj.name
        inputName.value = newObj.name
    }

    setTimeout(() => {
        obj.name = '测试数据'
    },1000)

    inputName.oninput = function() {
         obj.name = this.value
    }


</script>

</html>
posted @ 2021-03-11 23:02  Smile浅笑  阅读(82)  评论(0编辑  收藏  举报