Proxy可以理解成,在目标对象之前架设一层 “拦截”,当外界对该对象访问的时候,都必须经过这层拦截,而Proxy就充当了这种机制,类似于代理的含义,它可以对外界访问对象之前进行过滤和改写该对象。
- 我们直接上代码:
html:
<fieldset>
<legend>proxy双向数据绑定</legend>
<label for="uname">姓名:<input type="text" id="uname" v-model="uName"></label><br>
<label for="upass">密码:<input type="password" id="upass" v-model="uPass"></label>
<hr>
<!-- 实时变化 -->
姓名:<h4 v-bind="uName"></h4><br>
密码:<h4 v-bind="uPass"></h4>
</fieldset>
js:
<script>
'use strict'
function View() {
const user = {}
let proxy = new Proxy(user, {
get(obj, property){},
set(obj, property, value){}
})
this.init = function (){
let inputs = document.querySelectorAll('[v-model]')
// console.log(inputs);
void [...inputs].map(item => {
item.addEventListener('keyup', function(){
console.log(this.value);
})
})
}
}
new View().init()
</script>
到此实现的更新状态,接下来渲染到页面
js-实时更新渲染
<script>
'use strict'
function View() {
const user = {}
let proxy = new Proxy(user, {
get(obj, property){
return obj[property]
},
set(obj, property, value){
// 数据存储
obj[property] = value
// 渲染
document.querySelector(`[v-bind="${property}"]`).innerHTML = value
return Reflect.set(obj, property, value);
// Reflect.set()方法允许你在对象上设置属性。它的作用是给属性赋值并且就像 property accessor 语法一样,但是它是以函数的方式。
// 设置成功true, 反之 false
// return true
}
})
this.init = function (){
let inputs = document.querySelectorAll('[v-model]')
// console.log(inputs);
void [...inputs].map(item => {
item.addEventListener('keyup', function(){
// console.log(this.value);
proxy[this.getAttribute('v-model')] = this.value
console.log(user);
})
})
}
}
new View().init()
</script>