2 Star 11 Fork 1

ifer / vue3_71

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
双向数据绑定原理.html 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
ifer 提交于 2022-04-11 09:20 . .
<!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>Document</title>
</head>
<body>
<p id="oP"></p>
<input id="oInput" type="text">
<script>
// 需求:双向数据绑定(数据变了,视图改变;视图改变,数据也变)
const data = {
name: 'ifer',
address: '北京',
};
/* const tempData = { ...data }
Object.keys(data).forEach(key => {
Object.defineProperty(data, key, {
get() {
return tempData[key]
},
set(newValue) {
tempData[key] = newValue
oP.innerHTML = newValue
oInput.value = newValue
}
})
})
oInput.oninput = function (e) {
data.address = e.target.value
} */
// 上面 Vue2 的问题:如果 data 里面有 100 个属性,那可不是要循环 100 次吗?
// p 就是一个代理,我对 p 的任何操作都会影响到 data
const p = new Proxy(data, {
get(target, attr) {
// 获取的时候触发
// console.log(target, attr)
// target => data
// attr => 属性
return target[attr]
},
set(target, attr, newValue) {
target[attr] = newValue
oP.innerHTML = newValue
oInput.value = newValue
}
})
// p.name = 'xxx'
// console.log(data.name);
/* p.name = 'xxx'
console.log(p.name) */
oInput.oninput = function (e) {
// p.address = e.target.value
p.test = e.target.value
};
</script>
</body>
</html>
1
https://gitee.com/ifercarly/v3_71.git
git@gitee.com:ifercarly/v3_71.git
ifercarly
v3_71
vue3_71
master

搜索帮助