时间:2022-12-06 01:48
vue中双向数据绑定是通过数据劫持结合发布订阅模式的方式来实现的,其核心方法是Object.defineProperty()方法。
实现双向数据绑定的示例:
<!DOCTYPEhtml><html>
<head>
<metacharset="utf-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<title></title>
</head>
<body>
<inputtype="text"id="userName">
<br/>
<spanid="uName"></span>
<scripttype="text/javascript">
varobj={
pwd:"123456"
};
Object.defineProperty(obj,"userName",{
get:function(){
console.log("getinit");
},
set:function(val){
console.log("setinit");
document.getElementById("uName").innerText=val;
document.getElementById("userName").value=val;
}
});
document.getElementById("userName").addEventListener("keyup",function(){
obj.userName=event.target.value;
});
</script>
</body>
</html>