Vue Object.defineProperty及ProxyVue实现双向数据绑定


Posted in Javascript onSeptember 02, 2020

双向数据绑定无非就是,视图 => 数据,数据 => 视图的更新过程

Vue Object.defineProperty及ProxyVue实现双向数据绑定

以下的方案中的实现思路:

  • 定义一个Vue的构造函数并初始化这个函数(myVue.prototype._init)
  • 实现数据层的更新:数据劫持,定义一个 obverse 函数重写data的set和get(myVue.prototype._obsever)
  • 实现视图层的更新:订阅者模式,定义个 Watcher 函数实现对DOM的更新(Watcher)
  • 将数据和视图层进行绑定,解析指令v-bind、v-model、v-click(myVue.prototype._compile)
  • 创建Vue实例(new myVue)

1.object.defineproperty方式实现双向数据绑定

<!DOCTYPE html>
<html>
 
<head>
 <title>myVue</title>
 <style>
  #app{
  text-align: center;
 }
</style>
</head>
 
<body>
 <div id="app">
  <form>
   <input type="text" v-model="number" />
   <button type="button" v-click="increment">增加</button>
  </form>
  <h3 v-bind="number"></h3>
 </div>
</body>
<script>
 
 // 定义一个myVue构造函数
 function myVue(option) {
  this._init(option)
 }
 
 myVue.prototype._init = function (options) { // 传了一个配置对象
  this.$options = options // options 为上面使用时传入的结构体,包括el,data,methods
  this.$el = document.querySelector(options.el) // el是 #app, this.$el是id为app的Element元素
  this.$data = options.data // this.$data = {number: 0}
  this.$methods = options.methods // this.$methods = {increment: function(){}}
 
 
  // _binding保存着model与view的映射关系,也就是我们前面定义的Watcher的实例。当model改变时,我们会触发其中的指令类更新,保证view也能实时更新
  this._binding = {}
 
  this._obsever(this.$data)
  this._compile(this.$el)
 }
 
 // 数据劫持:更新数据
 myVue.prototype._obsever = function (obj) {
  let _this = this
  Object.keys(obj).forEach((key) => { // 遍历obj对象
   if (obj.hasOwnProperty(key)) { // 判断 obj 对象是否包含 key属性
    _this._binding[key] = [] // 按照前面的数据,_binding = {number: []} 存储 每一个 new Watcher
   }
   let value = obj[key]
   if (typeof value === 'object') { //如果值还是对象,则遍历处理
    _this._obsever(value)
   }
   Object.defineProperty(_this.$data, key, {
    enumerable: true,
    configurable: true,
    get: () => { // 获取 value 值
     return value
    },
    set: (newVal) => { // 更新 value 值
     if (value !== newVal) {
      value = newVal
      _this._binding[key].forEach((item) => { // 当number改变时,触发_binding[number] 中的绑定的Watcher类的更新
       item.update() // 调 Watcher 实例的 update 方法更新 DOM
      })
     }
    }
   })
  })
 }
 
 // 订阅者模式: 绑定更新函数,实现对 DOM 元素的更新
 function Watcher(el, data, key, attr) {
  this.el = el // 指令对应的DOM元素
  this.data = data // this.$data 数据: {number: 0, count: 0}
  this.key = key // 指令绑定的值,本例如"number"
  this.attr = attr // 绑定的属性值,本例为"innerHTML","value"
 
  this.update()
 }
 // 比如 H3.innerHTML = this.data.number; 当number改变时,会触发这个update函数,保证对应的DOM内容进行了更新
 Watcher.prototype.update = function () {
  this.el[this.attr] = this.data[this.key]
 }
 
 // 将view与model进行绑定,解析指令(v-bind,v-model,v-clickde)等
 myVue.prototype._compile = function (el) { // root 为id为app的Element元素,也就是我们的根元素
  let _this = this
  let nodes = Array.prototype.slice.call(el.children) // 将为数组转化为真正的数组
  nodes.map(node => {
   if (node.children.length && node.children.length > 0) { // 对所有元素进行遍历,并进行处理
    _this._compile(node)
   }
   if (node.hasAttribute('v-click')) { // 如果有v-click属性,我们监听它的onclick事件,触发increment事件,即number++
    let attrVal = node.getAttribute('v-click')
    node.onclick = _this.$methods[attrVal].bind(_this.$data) // bind是使data的作用域与method函数的作用域保持一致
   }
 
   // 如果有v-model属性,并且元素是INPUT或者TEXTAREA,我们监听它的input事件
   if (node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')) {
    let attrVal = node.getAttribute('v-model')
 
    _this._binding[attrVal].push(new Watcher(
     node, // 对应的 DOM 节点
     _this.$data,
     attrVal, // v-model 绑定的值
     'value'
    ))
    node.addEventListener('input', () => {
     _this.$data[attrVal] = node.value // 使number 的值与 node的value保持一致,已经实现了双向绑定
    })
   }
   if (node.hasAttribute('v-bind')) {
    let attrVal = node.getAttribute('v-bind')
    _this._binding[attrVal].push(new Watcher(
     node,
     _this.$data,
     attrVal, // v-bind 绑定的值
     'innerHTML'
    ))
   }
  })
 }
 
 
 window.onload = () => { // 当文档内容完全加载完成会触发该事件,避免获取不到对象的情况
  new myVue({
   el: '#app',
   data: {
    number: 0,
    count: 0
   },
   methods: {
    increment() {
     this.number++
    },
    incre() {
     this.count++
    }
   }
  })
 }
</script>
 
</html>

2.Proxy 实现双向数据绑定

<!DOCTYPE html>
<html>
 
<head>
 <title>myVue</title>
 <style>
  #app{
  text-align: center;
 }
</style>
</head>
 
<body>
 <div id="app">
  <form>
   <input type="text" v-model="number" />
   <button type="button" v-click="increment">增加</button>
  </form>
  <h3 v-bind="number"></h3>
 </div>
</body>
<script>
 
 // 定义一个myVue构造函数
 function myVue(option) {
  this._init(option)
 }
 
 myVue.prototype._init = function (options) { // 传了一个配置对象
  this.$options = options // options 为上面使用时传入的结构体,包括el,data,methods
  this.$el = document.querySelector(options.el) // el是 #app, this.$el是id为app的Element元素
  this.$data = options.data // this.$data = {number: 0}
  this.$methods = options.methods // this.$methods = {increment: function(){}}
 
  this._binding = {}
  this._obsever(this.$data)
  this._complie(this.$el)
 
 }
 
// 数据劫持:更新数据
myVue.prototype._obsever = function (data) {
  let _this = this
  let handler = {
   get(target, key) {
    return target[key]; // 获取该对象上key的值
   },
   set(target, key, newValue) {
    let res = Reflect.set(target, key, newValue); // 将新值分配给属性的函数
    _this._binding[key].map(item => {
     item.update();
    });
    return res;
   }
  };
  // 把代理器返回的对象代理到this.$data,即this.$data是代理后的对象,外部每次对this.$data进行操作时,实际上执行的是这段代码里handler对象上的方法
  this.$data = new Proxy(data, handler);
 }
 
 // 将view与model进行绑定,解析指令(v-bind,v-model,v-clickde)等
 myVue.prototype._complie = function (el) { // el 为id为app的Element元素,也就是我们的根元素
  let _this = this
  let nodes = Array.prototype.slice.call(el.children) // 将为数组转化为真正的数组
 
  nodes.map(node => {
   if (node.children.length && node.children.length > 0) this._complie(node)
   if (node.hasAttribute('v-click')) { // 如果有v-click属性,我们监听它的onclick事件,触发increment事件,即number++
    let attrVal = node.getAttribute('v-click')
    node.onclick = _this.$methods[attrVal].bind(_this.$data) // bind是使data的作用域与method函数的作用域保持一致
   }
 
   // 如果有v-model属性,并且元素是INPUT或者TEXTAREA,我们监听它的input事件
   if (node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')) {
    let attrVal = node.getAttribute('v-model')
    
    console.log(_this._binding)
    if (!_this._binding[attrVal]) _this._binding[attrVal] = []
    _this._binding[attrVal].push(new Watcher(
     node, // 对应的 DOM 节点
     _this.$data,
     attrVal, // v-model 绑定的值
     'value',
    ))
    node.addEventListener('input', () => {
     _this.$data[attrVal] = node.value // 使number 的值与 node的value保持一致,已经实现了双向绑定
    })
   }
   if (node.hasAttribute('v-bind')) {
    let attrVal = node.getAttribute('v-bind')
    if (!_this._binding[attrVal]) _this._binding[attrVal] = []
    _this._binding[attrVal].push(new Watcher(
     node,
     _this.$data,
     attrVal, // v-bind 绑定的值
     'innerHTML',
    ))
   }
 
  })
 }
 // 绑定更新函数,实现对 DOM 元素的更新
 function Watcher(el, data, key, attr) {
  this.el = el // 指令对应的DOM元素
  this.data = data // 代理的对象 this.$data 数据: {number: 0, count: 0}
  this.key = key // 指令绑定的值,本例如"num"
  this.attr = attr // 绑定的属性值,本例为"innerHTML","value"
 
  this.update()
 }
 // 比如 H3.innerHTML = this.data.number; 当number改变时,会触发这个update函数,保证对应的DOM内容进行了更新
 Watcher.prototype.update = function () {
  this.el[this.attr] = this.data[this.key]
 }
 
 window.onload = () => { // 当文档内容完全加载完成会触发该事件,避免获取不到对象的情况
  new myVue({
   el: '#app',
   data: {
    number: 0,
    count: 0
   },
   methods: {
    increment() {
     this.number++
    },
    incre() {
     this.count++
    }
   }
  })
 }
</script>
 
</html>

3.将上面代码改成class的写法

<!DOCTYPE html>
<html>
 
<head>
 <title>myVue</title>
 <style>
  #app{
  text-align: center;
 }
</style>
</head>
 
<body>
 <div id="app">
  <form>
   <input type="text" v-model="number" />
   <button type="button" v-click="increment">增加</button>
  </form>
  <h3 v-bind="number"></h3>
 </div>
</body>
<script>
 
 class MyVue {
  constructor(options) { // 接收了一个配置对象
   this.$options = options // options 为上面使用时传入的结构体,包括el,data,methods
   this.$el = document.querySelector(options.el) // el是 #app, this.$el是id为app的Element元素
   this.$data = options.data // this.$data = {number: 0}
   this.$methods = options.methods // this.$methods = {increment: function(){}}
 
   this._binding = {}
   this._obsever(this.$data)
   this._complie(this.$el)
  }
  _obsever (data) { // 数据劫持:更新数据
   let _this = this
   let handler = {
    get(target, key) {
     return target[key]; // 获取该对象上key的值
    },
    set(target, key, newValue) {
     let res = Reflect.set(target, key, newValue); // 将新值分配给属性的函数
     _this._binding[key].map(item => {
      item.update();
     });
     return res;
    }
   };
   // 把代理器返回的对象代理到this.$data,即this.$data是代理后的对象,外部每次对this.$data进行操作时,实际上执行的是这段代码里handler对象上的方法
   this.$data = new Proxy(data, handler);
  }
  _complie(el) { // el 为id为app的Element元素,也就是我们的根元素
   let _this = this
   let nodes = Array.prototype.slice.call(el.children) // 将为数组转化为真正的数组
 
   nodes.map(node => {
    if (node.children.length && node.children.length > 0) this._complie(node)
    if (node.hasAttribute('v-click')) { // 如果有v-click属性,我们监听它的onclick事件,触发increment事件,即number++
     let attrVal = node.getAttribute('v-click')
     node.onclick = _this.$methods[attrVal].bind(_this.$data) // bind是使data的作用域与method函数的作用域保持一致
    }
 
    // 如果有v-model属性,并且元素是INPUT或者TEXTAREA,我们监听它的input事件
    if (node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')) {
     let attrVal = node.getAttribute('v-model')
     if (!_this._binding[attrVal]) _this._binding[attrVal] = []
     _this._binding[attrVal].push(new Watcher(
      node, // 对应的 DOM 节点
      _this.$data,
      attrVal, // v-model 绑定的值
      'value',
     ))
     node.addEventListener('input', () => {
      _this.$data[attrVal] = node.value // 使number 的值与 node的value保持一致,已经实现了双向绑定
     })
    }
    if (node.hasAttribute('v-bind')) {
     let attrVal = node.getAttribute('v-bind')
     if (!_this._binding[attrVal]) _this._binding[attrVal] = []
     _this._binding[attrVal].push(new Watcher(
      node,
      _this.$data,
      attrVal, // v-bind 绑定的值
      'innerHTML',
     ))
    }
 
   })
  }
 }
 
 class Watcher {
  constructor (el, data, key, attr) {
   this.el = el // 指令对应的DOM元素
   this.data = data // 代理的对象 this.$data 数据: {number: 0, count: 0}
   this.key = key // 指令绑定的值,本例如"num"
   this.attr = attr // 绑定的属性值,本例为"innerHTML","value"
   this.update()
  }
 
  update () {
   this.el[this.attr] = this.data[this.key]
  }
 }
 
 
 
 window.onload = () => { // 当文档内容完全加载完成会触发该事件,避免获取不到对象的情况
  new MyVue({
   el: '#app',
   data: {
    number: 0,
    count: 0
   },
   methods: {
    increment() {
     this.number++
    },
    incre() {
     this.count++
    }
   }
  })
 }
</script>
 
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JavaScript DOM 学习第七章 表单的扩展
Feb 19 Javascript
基于jQuery中对数组进行操作的方法
Apr 16 Javascript
JQuery实现鼠标移动到图片上显示边框效果
Jan 09 Javascript
什么是MEAN?JavaScript编程中的MEAN是什么意思?
Dec 18 Javascript
js实现漂浮回顶部按钮实例
May 06 Javascript
javascript先序遍历DOM树的方法
Feb 27 Javascript
js获取对象、数组的实际长度,元素实际个数的实现代码
Jun 08 Javascript
VUE 更好的 ajax 上传处理 axios.js实现代码
May 10 Javascript
Vue+mui实现图片的本地缓存示例代码
May 24 Javascript
vue+springboot实现项目的CORS跨域请求
Sep 05 Javascript
vue加载完成后的回调函数方法
Sep 07 Javascript
js利用拖放实现添加删除
Aug 27 Javascript
Vue 组件的挂载与父子组件的传值实例
Sep 02 #Javascript
vue中的.$mount('#app')手动挂载操作
Sep 02 #Javascript
vue中提示$index is not defined错误的解决方式
Sep 02 #Javascript
解决vue组件没显示,没起作用,没报错,但该显示的组件没显示问题
Sep 02 #Javascript
vue或react项目生产环境去掉console.log的操作
Sep 02 #Javascript
JS继承实现方法及优缺点详解
Sep 02 #Javascript
vue-cli3访问public文件夹静态资源报错的解决方式
Sep 02 #Javascript
You might like
php实现的常见排序算法汇总
2014/09/08 PHP
在SAE上搭建最新wordpress的方法
2014/12/21 PHP
php PDO实现的事务回滚示例
2017/03/23 PHP
PHP7内核CGI与FastCGI详解
2019/04/14 PHP
php使用filter_var函数判断邮箱,url,ip格式示例
2019/07/06 PHP
laravel执行php artisan migrate报错的解决方法
2019/10/09 PHP
JavaScript中出现乱码的处理心得
2009/12/24 Javascript
Jquery 例外被抛出且未被接住原因介绍
2013/09/04 Javascript
showModalDialog在谷歌浏览器下会返回Null的解决方法
2013/11/27 Javascript
JQuery EasyUI 加载两次url的原因分析及解决方案
2014/08/18 Javascript
基于AngularJS实现页面滚动到底自动加载数据的功能
2015/10/16 Javascript
Java框架SSH结合Easyui控件实现省市县三级联动示例解析
2016/06/12 Javascript
搭建Bootstrap离线文档的方法
2016/12/02 Javascript
AngularJS 使用ng-repeat报错 [ngRepeat:dupes]
2017/01/19 Javascript
vue+webpack实现异步加载三种用法示例详解
2018/04/24 Javascript
javascript数组常见操作方法实例总结【连接、添加、删除、去重、排序等】
2019/06/13 Javascript
layui问题之模拟table表格中的选中按钮选中事件的方法
2019/09/20 Javascript
jQuery使用ajax传递json对象到服务端及contentType的用法示例
2020/03/12 jQuery
prettier自动格式化去换行的实现代码
2020/08/25 Javascript
vue使用canvas实现移动端手写签名
2020/09/22 Javascript
详解node.js创建一个web服务器(Server)的详细步骤
2021/01/15 Javascript
从零学Python之入门(二)基本数据类型
2014/05/25 Python
Python使用type关键字创建类步骤详解
2019/07/23 Python
python的time模块和datetime模块实例解析
2019/11/29 Python
Python qrcode 生成一个二维码的实例详解
2020/02/12 Python
django实现模型字段动态choice的操作
2020/04/01 Python
基于Keras 循环训练模型跑数据时内存泄漏的解决方式
2020/06/11 Python
python3 简单实现组合设计模式
2020/07/02 Python
DJI全球:DJI Global
2021/03/15 全球购物
工地例会施工汇报材料
2014/08/22 职场文书
放飞梦想演讲稿200字
2014/08/26 职场文书
2014年教师节红领巾广播稿
2014/09/10 职场文书
《中国机长》观后感:敬畏生命,敬畏职责
2019/11/12 职场文书
使用canvas实现雪花飘动效果的示例代码
2021/03/30 HTML / CSS
python3 实现mysql数据库连接池的示例代码
2021/04/17 Python
关于Javascript闭包与应用的详解
2021/04/22 Javascript