前言

在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理。本篇文章中我将会仿照vue写一个双向数据绑定的实例,名字就叫myVue吧。结合注释,希望能让大家有所收获。

原理

Vue的双向数据绑定的原理相信大家也都十分了解了,主要是通过Object对象的defineProperty属性,重写data的set和get函数来实现的,这里对原理不做过多描述,主要还是来实现一个实例。为了使代码更加的清晰,这里只会实现最基本的内容,主要实现v-model,v-bind 和v-click三个命令,其他命令也可以自行补充。

添加网上的一张图

实现

页面结构很简单,如下

<div id="app"><form><input type="text"  v-model="number"><button type="button" v-click="increment">增加</button></form><h3 v-bind="number"></h3></div>
复制代码

包含:

1. 一个input,使用v-model指令
2. 一个button,使用v-click指令
3. 一个h3,使用v-bind指令。
复制代码

我们最后会通过类似于vue的方式来使用我们的双向数据绑定,结合我们的数据结构添加注释

var app = new myVue({el:'#app',data: {number: 0},methods: {increment: function() {this.number ++}}
})
复制代码

首先我们需要定义一个myVue构造函数:

function myVue(options) {}
复制代码

为了初始化这个构造函数,给它添加一个_init属性

function myVue(options) {
this._init(options);
}
myVue.prototype._init = function (options) {this.$options = options;  // options 为上面使用时传入的结构体,包括el,data,methodsthis.$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(){}}
}
复制代码

接下来实现_obverse函数,对data进行处理,重写data的set和get函数,并改造_init函数

myVue.prototype._obverse = function (obj) { // obj = {number: 0}var value;for (key in obj) {  //遍历obj对象if (obj.hasOwnProperty(key)) {value = obj[key]; if (typeof value === 'object') {  //如果值还是对象,则遍历处理this._obverse(value);}Object.defineProperty(obj, key, {  //关键enumerable: true,configurable: true,get: function () {console.log(`获取${value}`);return value;},set: function (newVal) {console.log(`更新${newVal}`);if (value !== newVal) {value = newVal;}}})}}
}
myVue.prototype._init = function (options) {this.$options = options;this.$el = document.querySelector(options.el);this.$data = options.data;this.$methods = options.methods;// 劫持data进行双向数据绑定this._obverse(this.$data);
}
复制代码

接下来我们写一个指令类Watcher,用来绑定更新函数,实现对DOM元素的更新

function Watcher(name, el, vm, exp, attr) {this.name = name;         //指令名称,例如文本节点,该值设为"text"this.el = el;             //指令对应的DOM元素this.vm = vm;             //指令所属myVue实例this.exp = exp;           //指令对应的值,本例如"number"this.attr = attr;         //绑定的属性值,本例为"innerHTML"// 更新this.update();}Watcher.prototype.update = function () {// 比如 H3.innerHTML = this.data.number;// 当number改变时,会触发这个update函数,保证对应的DOM内容进行了更新。this.el[this.attr] = this.vm.$data[this.exp];
}
复制代码

更新_init函数以及_obverse函数

myVue.prototype._init = function (options) {//...this._binding = {};   // _binding保存着model与view的映射关系,也就是我们前面定义的Watcher的实例。// 当model改变时,我们会触发其中的指令类更新,保证view也能实时更新//...
}myVue.prototype._obverse = function (obj) {//...if (obj.hasOwnProperty(key)) {// 按照前面的数据,_binding = {number: _directives: []}  this._binding[key] = {_directives: []};//...var binding = this._binding[key];Object.defineProperty(this.$data, key, {//...set: function (newVal) {console.log(`更新${newVal}`);if (value !== newVal) {value = newVal;binding._directives.forEach(function (item) {  // 当number改变时,触发_binding[number]._directives 中的绑定的Watcher类的更新item.update();})}}})}
}
复制代码

那么如何将view与model进行绑定呢?接下来我们定义一个_compile函数,用来解析我们的指令(v-bind,v-model,v-clickde)等,并在这个过程中对view与model进行绑定。

myVue.prototype._init = function (options) {//...this._complie(this.$el);
}
myVue.prototype._complie = function (root) { // root 为 id为app的Element元素,也就是我们的根元素var _this = this;var nodes = root.children;for (var i = 0; i < nodes.length; i++) {var node = nodes[i];if (node.children.length) {  // 对所有元素进行遍历,并进行处理this._complie(node);}if (node.hasAttribute('v-click')) { // 如果有v-click属性,我们监听它的onclick事件,触发increment事件,即number++node.onclick = (function () {var attrVal = nodes[i].getAttribute('v-click');return _this.$methods[attrVal].bind(_this.$data); // {number:1} //bind是使data的作用域与method函数的作用域保持一致})();}if (node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')){// 如果有v-model属性,并且元素是INPUT或者TEXTAREA,我们监听它的input事件node.addEventListener('input', (function(key) {  var attrVal = node.getAttribute('v-model');// _this._binding['number']._directives = [一个Watcher实例]// 其中Watcher.prototype.update = function () {//   node['vaule'] = _this.$data['number'];  这就将node的值保持与number一致// }_this._binding[attrVal]._directives.push(new Watcher(  'input',node,_this,attrVal,'value'))return function() {_this.$data[attrVal] =  nodes[key].value; // 使number 的值与 node的value保持一致,已经实现了双向绑定}})(i));} if (node.hasAttribute('v-bind')) { // 如果有v-bind属性,我们只要使node的值及时更新为data中number的值即可var attrVal = node.getAttribute('v-bind');_this._binding[attrVal]._directives.push(new Watcher('text',node,_this,attrVal,'innerHTML'))}}}
复制代码

至此,我们已经实现了一个简单vue的双向绑定功能,包括v-bind, v-model, v-click三个指令。效果如下图

附上全部代码,不到150行

<!DOCTYPE html>
<head><title>myVue</title>
</head>
<style>#app {text-align: center;}
</style>
<body><div id="app"><form><input type="text"  v-model="number"><button type="button" v-click="increment">增加</button></form><h3 v-bind="number"></h3><form><input type="text"  v-model="count"><button type="button" v-click="incre">减少</button></form><h3 v-bind="count"></h3></div>
</body><script>
window.onload = function() {var app = new myVue({el:'#app',data: {number: 0,count: 0,},methods: {increment: function() {this.number++;},incre: function() {this.count--;}}})
}
// 定义myVue
function myVue(options) {this._init(options);
}
// 入口
myVue.prototype._init = function (options) {this.$options = options;this.$el = document.querySelector(options.el);this.$data = options.data;this.$methods = options.methods;this._binding = {};this._obverse(this.$data);this._complie(this.$el);
}
// 数据劫持-双向数据绑定
myVue.prototype._obverse = function (obj) {var _this = this;Object.keys(obj).forEach(function (key) {if (obj.hasOwnProperty(key)) {_this._binding[key] = {_directives:[]};console.log(_this._binding[key])var value = obj[key];if (typeof value === 'object') {_this._obverse(value);}var binding = _this._binding[key];Object.defineProperty(_this.$data, key, {enumerable: true,configurable: true,get: function () {console.log(`${key}获取${value}`);return value;},set: function (newVal) {console.log(`${key}更新${newVal}`);if (value !== newVal) {value = newVal;binding._directives.forEach(function (item) {item.update();})}}})}})
}
// dom的指令解析
myVue.prototype._complie = function (root) {var _this = this;var nodes = root.children;for (var i = 0; i < nodes.length; i++) {var node = nodes[i];if (node.children.length) {this._complie(node);}if (node.hasAttribute('v-click')) {node.onclick = (function () {var attrVal = nodes[i].getAttribute('v-click');return _this.$methods[attrVal].bind(_this.$data);})();}if (node.hasAttribute('v-model') && (node.tagName = 'INPUT' || node.tagName == 'TEXTAREA')) {node.addEventListener('input', (function(key) {var attrVal = node.getAttribute('v-model');_this._binding[attrVal]._directives.push(new Watcher('input',node,_this,attrVal,'value'))return function() {_this.$data[attrVal] =  nodes[key].value;}})(i));} if (node.hasAttribute('v-bind')) {var attrVal = node.getAttribute('v-bind');_this._binding[attrVal]._directives.push(new Watcher('text',node,_this,attrVal,'innerHTML'))}}
}
function Watcher(name, el, vm, exp, attr) {this.name = name;         //指令名称,例如文本节点,该值设为"text"this.el = el;             //指令对应的DOM元素this.vm = vm;             //指令所属myVue实例this.exp = exp;           //指令对应的值,本例如"number"this.attr = attr;         //绑定的属性值,本例为"innerHTML"// 更新试图this.update();
}
Watcher.prototype.update = function () {this.el[this.attr] = this.vm.$data[this.exp];
}
</script>
复制代码

深入了解Vue的双向数据绑定相关推荐

  1. vue的双向数据绑定的原理

    VUE实现双向数据绑定的原理就是利用了 Object.defineProperty() 这个方法重新定义了对象获取属性值(get)和设置属性值(set)的操作来实现的. 代码演示:defineProp ...

  2. Vue的双向数据绑定原理(极简版)

    先说面试答案: 答: vue.js是采用数据劫持结合发布者-订阅者模式的方式,通过Object.defineProperty()来劫持各个属性的setter,getter,在数据变动时发布消息给订阅者 ...

  3. 【Vue的双向数据绑定原理】

    Vue的双向数据绑定原理 先说面试答案: 1. 什么是setter.getter 2. 什么是Object.defineProperty() ? 先简单的实现一个js的双向数据绑定来熟悉一下`Obje ...

  4. Vue v-model双向数据绑定和一个简单的整数计算器

    一.v-model双向数据绑定 方法 v-bind - 单向数据绑定(从M到V) v-model - 双向数据绑定 例子 <input type="text" v-bind: ...

  5. 手写Vue 的双向数据绑定

    在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理. 本篇文章中我将会仿照vue写一个双向数据绑定的实例,名字就叫myVue吧.结合注释,希 ...

  6. 面试题:你能写一个Vue的双向数据绑定吗?

    在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理.本篇文章中我将会仿照vue写一个双向数据绑定的实例,名字就叫myVue吧.结合注释,希望 ...

  7. 面试题:你能写一个 Vue 的双向数据绑定吗?

    作者:呆头呆脑丶 segmentfault.com/a/1190000014274840 在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理 ...

  8. 写一个Vue的双向数据绑定

    原文 https://segmentfault.com/a/1190000014274840 在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出 ...

  9. 你能写一个 Vue 的双向数据绑定吗?

    在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理.本篇文章中我将会仿照vue写一个双向数据绑定的实例,名字就叫myVue吧.结合注释,希望 ...

最新文章

  1. 2022-2028年中国可生物降解农用薄膜产业竞争现状及投资决策建议报告
  2. 学计算机excel就很好吗,零基础学习excel小技巧
  3. 智能制造业乘风破浪,工业机器人怎样勇立潮头?
  4. ssh中exit命令退出远程服务器_解决Linux关闭终端(关闭SSH等)后运行的程序或者服务自动停止...
  5. php中getdistance函数_php代码渗透测试 后门分析篇
  6. 程序员能力提升:你应该知道的那些编程原则!!
  7. CesiumJS 2022^ 原理[2] 渲染架构之三维物体 - 创建并执行指令
  8. 软考信息系统项目管理师_信息系统项目管理基础---软考高级之信息系统项目管理师008
  9. 达梦数据charindex_更新日志 · dotnetcore/FreeSql Wiki · GitHub
  10. python类添加方法以及pow和cmp的使用
  11. python微信开发入门_python tornado微信开发入门代码
  12. window.showModalDialog用法
  13. Linux下载工具photon,不限速、免配置的 Aria2 免费开源下载软件 Photon,替代迅雷的...
  14. Python电商数据分析实战案例
  15. win7计算机打印机共享权限设置,win7共享打印机(没有权限访问)
  16. 【工控安全产品】工控主机卫士
  17. R485集线器定协议有多少种能否抗干扰?
  18. iphone粘贴关联_如何将电话号码粘贴到iPhone的电话应用程序中
  19. 2022年全国计算机四级考试精选模拟题及答案
  20. 仰望流年纯白世界那抹城光(二)

热门文章

  1. c语言点餐对话系统,智能点餐系统的设计与实现.pdf
  2. 二分查找算法【C语言实现】
  3. 计算机的组成部件及其厂商
  4. staruml2.8 破解
  5. 不只是折腾!OS X 10.10 Yosemite 改造攻略
  6. uni.showModal使用
  7. 数据分析入门系列教程-常用图表
  8. 最新!芯片行业有哪些知名企业?
  9. python成绩表格
  10. Spring5的IOC原理解析