JavaScript实现Vue的双向绑定

1
2
3
4
<div>
<input type="text" id="input">
<div id="show"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var obj = {};

Object.defineProperty(obj, 'txt', {
configurable: true,
enumerable: true,
get: function () {
return obj;
},
set: function (newValue) {
document.getElementById('input').value = newValue;
document.getElementById('show').innerText = newValue;
}
});

document.addEventListener('keyup', function (e) {
obj.txt = e.target.value;
});