一个非常简陋的Vue双向绑定实现
程序员文章站
2024-03-01 17:18:34
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>双向绑定</title>
<Style>
body,
html {
margin: 0;
width: 100%;
height: 100%;
}
.main {
width: 100px;
height: 50px;
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 50px);
}
</Style>
</head>
<body>
<div class="main">
<span id="spa">123</span>
<input id="ipt" type="text" value="" oninput="change(value)">
<button onclick="ckl()">click</button>
</div>
</body>
<script>
let Book = { id: '1', male: '逍遥哥哥', female: '灵儿妹妹',list:[
{
index:1
},
{
index:2
},
{
index:3
}
] };
function defineProperty(data, key, val) {
observer(val);
Object.defineProperty(data, key, {
set: (newVal) => {
console.log('属性' + key + '已经被监听了,现在值为:' + newVal.toString() + '');
document.getElementById("spa").innerHTML = newVal;
document.getElementById("ipt").value = newVal;
},
get: () => {
return val
}
})
}
function observer(params) {
if (!params || typeof params !== 'object') {
return;
}
Object.keys(params).forEach(function (key) {
defineProperty(params, key, params[key])
});
}
observer(Book);
function change(params) {
console.log("params",params)
Book.male = params
}
function ckl(params) {
Book.male = 'Hello Vue'
}
</script>
</html>