vue数据响应式的理解

vue数据响应式的理解

当数据变化时会自动运行相关的函数


代码示例

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<div>
姓名: <input type="text" id="stuName"></input>
<br/>
年龄: <input type="text" id="stuAge"></input>
</div>

<script>
//1、观察对象的所有属性
//2、遍历对象的所以属性
//3、当对象属性发生变化时自动调用依赖该属性的函数

function observe(obj) {
    for (const key in obj) {
        let innerVal = obj[key];
        let funcs = [];
        Object.defineProperty(obj, key, {
            //依赖收集,记录哪个函数在调用
            //还是不知道函数名是什么?定义一个全局变量来存函数名

            //读取属性值时触发get函数
            get() {
                if (window.__func && !funcs.includes(window.__func)) {
                    funcs.push(window.__func);
                }
                return innerVal;
            },
            //属性值发生变化时触发set函数
            set(newVal) {
                if (innerVal === newVal) {
                    return;
                }
                innerVal = newVal;
                //触发依赖该属性的函数???不知道哪些函数用到了属性???
                //set不知道,get知道,get里面记录函数名(依赖收集)

                //调用依赖该属性的函数
                for (let i = 0; i < funcs.length; i++) {
                    funcs[i]();
                }
                console.log(key + "属性发生变化");
            }
        });
    }
}

function autoRun(fn) {
    window.__func = fn;
    fn();
    window.__func = null;
}

</script>


<script>
var stu = {
    stuName: '张三',
    stuAge: 18
};

observe(stu);

function showName() {
    document.getElementById('stuName').value = stu.stuName;
}

function showAge() {
    document.getElementById('stuAge').value = stu.stuAge;
}

showName();
showAge();
autoRun(showName);
autoRun(showAge);

// 用于测试属性变化的代码
setTimeout(() => {
    stu.stuName = '李四';
    stu.stuAge = 20;
}, 2000);
</script>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值