Vue如何实现双向数据绑定?
.Object.defineProperty()函数
<!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>
</head>
<body>
<input type="text" id="a">
<span id="b"></span>
<script>
var obj = {};
Object.defineProperty(obj,'hello',{
set: function(newVal) {
document.getElementById('a').value = newVal;
document.getElementById('b').innerHTML = newVal;
}
});
document.addEventListener('keyup',function (e){
obj.hello = e.target.value;
});
</script>
</body>
</html>
在实际的运行过程中,defineProperty()里面会触发set init()或者get ini() 这两个方法进行监听。