2rever的前端小站

实现Vue双向绑定

Word count: 292 / Reading time: 2 min
2019/03/30 Share

Vue双向绑定的实现

es5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!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>
<script>
const obj = {
value: ''
}

function onKeyUp(event) {
obj.value = event.target.value
}

// 对 obj.value 进行拦截
Object.defineProperty(obj, 'value', {
get: function() {
return value
},
set: function(newValue) {
value = newValue
document.querySelector('#value').innerHTML = newValue // 更新视图层
document.querySelector('input').value = newValue // 数据模型改变
}
})
</script>
</head>
<body>
<p>
值是:<span id="value"></span>
</p>
<input type="text" onkeyup="onKeyUp(event)">
</body>
</html>

es6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!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>
<script>
const obj = {}

const newObj = new Proxy(obj, {
get: function(target, key, receiver) {
return Reflect.get(target, key, receiver)
},
set: function(target, key, value, receiver) {
if(key === 'value') {
document.querySelector('#value').innerHTML = value
document.querySelector('input').value = value
}
return Reflect.set(target, key, value, receiver)
}
})

function onKeyUp(event) {
newObj.value = event.target.value
}

</script>
</head>
<body>
<p>
值是:<span id="value"></span>
</p>
<input type="text" onkeyup="onKeyUp(event)">
</body>
</html>
CATALOG
  1. 1. Vue双向绑定的实现
    1. 1.1. es5
    2. 1.2. es6