示例1:Vue2.0 通过?Object.defineProperty 实现双向数据绑定原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue2.0 双向数据绑定原理</title>
</head>
<body>
文本:<span id="span"></span><br>
输入:<input type="text" id="input"><br>
<script>
let obj = {
name: ''
};
let newObj = JSON.parse(JSON.stringify(obj));
Object.defineProperty(obj, 'name', {
get() {
return newObj.name;
},
set(value) {
newObj.name = value;
observer()
}
})
// 给 sapn 赋值
function observer() {
span.innerHTML = obj.name;
input.value = obj.name;
}
// input 绑定事件
input.oninput = function () {
obj.name = input.value
}
// 数据更新视图
setTimeout(() => {
obj.name = 'ZS'
}, 1000);
</script>
</body>
</html>
示例2:Vue3.0 通过?Proxy?实现双向数据绑定原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3.0 双向数据绑定原理</title>
</head>
<body>
文本:<span id="span"></span><br>
输入:<input type="text" id="input"><br>
<script>
let obj = {};
obj = new Proxy(obj, {
/**
* target:对象
* prop:属性
* value:修改的值
* receiver:proxy实例
*/
get(target, prop, receiver) {
// console.log('get', target, prop, receiver);
return target[prop]
},
set(target, prop, value, receiver) {
// console.log('set', target, prop, value, receiver);
target[prop] = value
observer()
}
})
// 给 sapn 赋值
function observer() {
span.innerHTML = obj.name;
input.value = obj.name;
}
// input 绑定事件
input.oninput = function () {
obj.name = input.value
}
// 数据更新视图
setTimeout(() => {
obj.name = 'ZS'
}, 1000);
</script>
</body>
</html>
|