Vue.js中最让引人入胜的功能之一就是: 数据的双向绑定,下面使用原生JavaScript, 只须区区20行代码即可实现:
meta charset="utf-8"
<title>数据双向绑定</title>
<label>输入:<input id="input" type="text"></input id="input" type="text"></label>
p id="p"
<script>
let obj = {};
let input = document.getElementById('input');
let p = document.getElementById('p');
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('获取到数据了');
return obj.text;
},
set(newVal) {
console.log('数据更新了');
input.value = newVal;
p.innerHTML = newVal;
}
});
input.addEventListener('keyup', function (ev) {
obj.text = ev.target.value;
}, false);
</script>
">
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数据双向绑定</title>
</head>
<body>
<label>输入:<input id="input" type="text"></label>
<p id="p"></p>
<script>
let obj = {};
let input = document.getElementById('input');
let p = document.getElementById('p');
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('获取到数据了');
return obj.text;
},
set(newVal) {
console.log('数据更新了');
input.value = newVal;
p.innerHTML = newVal;
}
});
input.addEventListener('keyup', function (ev) {
obj.text = ev.target.value;
}, false);
</script>
</body>
</html>
版权属于:青城
本文链接:https://cloud.tencent.com/developer/article/1860311
转载时须注明出处及本声明