vue中雙向數據綁定是通過數據劫持結合發布訂閱模式的方式來實現的,其核心方法是Object.defineProperty()方法。
實現雙向數據綁定的示例:
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<input type="text" id="userName">
<br/>
<span id="uName"></span>
<script type="text/javascript">
var obj={
pwd:"123456"
};
Object.defineProperty(obj,"userName",{
get: function(){
console.log("get init");
},
set: function(val){
console.log("set init");
document.getElementById("uName").innerText=val;
document.getElementById("userName").value=val;
}
});
document.getElementById("userName").addEventListener("keyup",function(){
obj.userName=event.target.value;
});
</script>
</body>
</html>