proxy代理 |
您所在的位置:网站首页 › 简单实现双向绑定的方式 › proxy代理 |
Proxy可以理解成,在目标对象之前架设一层 “拦截”,当外界对该对象访问的时候,都必须经过这层拦截,而Proxy就充当了这种机制,类似于代理的含义,它可以对外界访问对象之前进行过滤和改写该对象。 我们直接上代码: html: proxy双向数据绑定 姓名: 密码: 姓名: 密码:js: '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()到此实现的更新状态,接下来渲染到页面 js-实时更新渲染 '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() |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |