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>