defineProperty
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="p"></p>
<input id="input" type="text" oninput="getChange(this)">
</body>
<script>
var p = document.querySelector('#p')
var input = document.querySelector('#input');
var a = {
value:'123'
};
p.innerHTML = a.value
input.value = a.value
Object.defineProperty(a,'value',{
get(val){
return val
},
set(val){
p.innerHTML = val
}
})
function getChange(val){
a.value = val.value
}
</script>
</html>
Proxy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="p"></p>
<input id="input" type="text" oninput="getChange(this)">
</body>
<script>
var p = document.querySelector('#p')
var input = document.querySelector('#input');
let a = {
value:'123'
};
let obj = new Proxy(a,{
get : function(target,prop) {
return prop in target ? target[prop] : 0 //可以给不存在的变量被声明时给一个默认值
},
set : function(target,prop,value){
p.innerHTML = value
}
})
console.log(obj.value1); // 0
p.innerHTML = obj.value
input.value = obj.value
function getChange(val){
obj.value = val.value
}
</script>
</html>
The updated version of vue3.0 will use Proxy to achieve the effect of two-way binding