Skip to content

Commit dd727cf

Browse files
authored
Create VUE双向绑定的简易实现.md
1 parent 7371ba4 commit dd727cf

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
双向绑定有多种实现方式,vue 是重写 Object 属性的 set 方法来实现的。
2+
3+
- **从 view 层到 Object 的绑定:** 监听 keyup 事件,把输入框的值赋值给需要绑定的对象
4+
- **从 Object 到 view 层的绑定:** 使用 Object.defineProperty 方法定义对象属性的 set 方法,在方法内同时对需要绑定的 view 层 value 进行改变,当用 = 表达式赋值时,会触发 set 方法。
5+
```javascript
6+
<html>
7+
<head>
8+
<script>
9+
var testData = {
10+
bindValue: "test"
11+
}
12+
var reInitalObj = function (obj) {
13+
Object.keys(obj).forEach(prop => {
14+
Object.defineProperty(obj, prop, {
15+
get: () => {
16+
return a_bind_value;
17+
},
18+
set: (value) => {
19+
document.getElementById('a-test-input').value = value;
20+
a_bind_value = value
21+
}
22+
});
23+
});
24+
}
25+
function load() {
26+
var a_bind_value;
27+
var theInput = document.getElementById('a-test-input');
28+
//从 Object 到 view 层的绑定
29+
reInitalObj(testData);
30+
31+
//从 view 层到 Object 的绑定
32+
document.addEventListener('keyup', function(e) {
33+
console.log('theInput.value:', theInput.value);
34+
testData.bindValue = theInput.value;
35+
}, false);
36+
}
37+
</script>
38+
</head>
39+
<body onload='load()'>
40+
<input id = 'a-test-input' />
41+
</body>
42+
</html>
43+
```

0 commit comments

Comments
 (0)