欢迎与我联系   

念两句诗

寄语洛城风日道,明年春色倍还人。
【唐代】杜审言《春日京中有怀》

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 @   小珍珠在河里敲代码  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2018-03-22 java多线程面试题整理及答案(2018年)
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多