一:通过Object.defineProperty实现效果
也就是Vue的数据双向绑定原理
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="input">
<h1></h1>
</body>
</html>
<script>
let inputElement = document.querySelector('#input');
let h1Element = document.querySelector('h1');
let Obj = {};
Object.defineProperty(Obj,'txt',{
set:function(value){
h1Element.innerHTML = value
}
})
inputElement.oninput = function(){
Obj.txt = this.value
}AA
</script>
二:使用ES6 class实现数据双向绑定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="input">
<h1></h1>
</body>
</html>
<script>
let inputElement = document.querySelector('#input');
let h1Element = document.querySelector('h1');
class Obj {
set txt(value){ //通过setter设置txt方法
h1Element.innerHTML = value
}
}
let watcher = new Obj(); //创建一个实例,赋值给watcher
inputElement.oninput = function(){
watcher.txt = this.value
}
</script>