欢迎与我联系   

vue2.0是如何监听双向绑定的?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            .contanier{
                width: 300px;
                height: 300px;
                background-color: aliceblue;
                border-radius: 10px;
            }
            .contanier-first,.contanier-second{
                text-align: left;
                font-size: 28px;
                padding: 30px 100px;
            }
        </style>
    </head>
    <body>
        <div class="contanier">
            <div class="contanier-first">
                <span>姓:</span>
                <span class="first"></span>
            </div>
            <div class="contanier-second">
                <span>名:</span>
                <span class="second"></span>
            </div>
        </div>
        <input type="text" oninput="userInfo.name=this.value"/>
    </body>
    <script src="./js/new.js"></script>
    <script src="./js/index.js"></script>
</html>
function observe(obj){
    for(const key in obj){
        let internalValue = obj[key];
        let funcs = [];
        Object.defineProperty(obj,key,{
            get(){
                if(window.__func && !funcs.includes(window.__func)){
                    funcs.push(window.__func);
                }
                return internalValue;
            },
            set(val){
                internalValue = val;
                for(var i=0;i<funcs.length;i++){
                    funcs[i]();
                }
            }
        })
    }
}

function autorun(fn){
    window.__func = fn;
    fn();
    window.__func = null;
}
const userInfo = {
    name: '张三丰'
}

observe(userInfo)

const firstPage = function () {
    const res = document.querySelector(".first");
    res.textContent = userInfo.name.charAt(0);
}

const secondPage = function () {
    const res = document.querySelector(".second");
    res.textContent = userInfo.name.slice(1);
}

autorun(firstPage);
autorun(secondPage);

userInfo.name = "陈独秀";

Object.defineProperty的缺点

如果data的层级过深,就会一次性递归到底,计算量很大。
Object.defineProperty无法监听新增、删除属性。 (vue中需使用$set();方法新增双向绑定属性)
Object.defineProperty不具备监听原生数组。

posted @ 2024-03-22 16:49  小珍珠在河里敲代码  阅读(16)  评论(0编辑  收藏  举报