vue-observe
2018-09-03 本文已影响0人
田帅奇
vue可以实现递归监听,因为变量地址引用的关系,还是闭包大法好,总觉得有点hack的感觉呢!
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
let data = {
name: 'zs',
age: 18,
like: {
walk: 'walk',
play: {
ball: 'baskball'
},
go: {
school: {
where: 'top'
}
}
}
};
var _data = {};
observe(data);
function observe (data) {
_data = data;
Object.keys(data).forEach(k => {
convert(k, data[k])
});
}
function convert (k,v) {
defineReactive(_data, k ,v)
}
function defineReactive (data, k, v) {
if (typeof v === 'object') {
observe(v);
}
Object.defineProperty(data, k, {
get: function () {
console.log('listen get');
return v;
},
set: function (nv) {
console.log('listen set');
if (nv === v) return
v = nv;
observe(nv);
}
});
}
console.log(data.like.go);
data.like.go = 1111;
console.log(data.like.go);
console.log(data.like);
</script>
</body>
</html>