目录

1、原理

2、实现


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

1、原理

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

添加网上的一张图

2、实现

页面结构很简单,如下

<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(this.$data, 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;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 () {this.el[this.attr] = this.vm.$data[this.exp]; //比如 H3.innerHTML = this.data.number; 当number改变时,会触发这个update函数,保证对应的DOM内容进行了更新。}

更新_init函数以及_obverse函数

myVue.prototype._init = function (options) {//...this._binding = {};   //_binding保存着model与view的映射关系,也就是我们前面定义的Watcher的实例。当model改变时,我们会触发其中的指令类更新,保证view也能实时更新//...}myVue.prototype._obverse = function (obj) {//...if (obj.hasOwnProperty(key)) {this._binding[key] = {    // 按照前面的数据,_binding = {number: _directives: []}                                                                                                                                                  _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);  //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></div>
</body><script>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 value;for (key in obj) {if (obj.hasOwnProperty(key)) {this._binding[key] = {                                                                                                                                                          _directives: []};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(`获取${value}`);return value;},set: function (newVal) {console.log(`更新${newVal}`);if (value !== newVal) {value = newVal;binding._directives.forEach(function (item) {item.update();})}}})}}}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];}window.onload = function() {var app = new myVue({el:'#app',data: {number: 0},methods: {increment: function() {this.number ++;},}})}
</script>

本面试题为前端常考面试题,后续有机会继续完善。我是歌谣,一个沉迷于故事的讲述者。

欢迎一起私信交流。

“睡服“面试官系列之各系列目录汇总(建议学习收藏)

“约见”面试官系列之常见面试题第九篇vue实现双向绑定原理(建议收藏)相关推荐

  1. “约见”面试官系列之常见面试题第四十一篇之VUE生命周期(建议收藏)

    详解Vue Lifecycle 先来看看VUE官网对VUE生命周期的介绍 Vue实例有一个完整的生命周期,也就是从开始创建.初始化数据.编译模板.挂载Dom.渲染→更新→渲染.销毁等一系列过程,我们称 ...

  2. “约见”面试官系列之常见面试题第二篇说说rem(建议收藏)

    目录 1.什么是rem? 2.为什么要用rem(rem有什么优点)? 怎样使用rem? 1.什么是rem? rem(font size of the root element)是指相对于根元素的字体大 ...

  3. “约见”面试官系列之常见面试题第一篇说说promise(建议收藏)

    目录 1前言 2promise是什么? 2.1举例说明 3异步操作的常见语法 3.1事件监听 3.2回调 4异步回调的问题: 5promise详解 6最简单示例: 1前言 这是来自江苏某公司的初级面试 ...

  4. “约见”面试官系列之常见面试题之第九十五篇之vue-router的组件组成(建议收藏)

    <router-link :to='' class='active-class'> //路由声明式跳转 ,active-class是标签被点击时的样式<router-view> ...

  5. “约见”面试官系列之常见面试题之第九十四篇之MVVM框架(建议收藏)

    目录 一句话总结:vm层(视图模型层)通过接口从后台m层(model层)请求数据,vm层继而和v(view层)实现数据的双向绑定. 1.我大前端应该不应该做复杂的数据处理的工作? 2.mvc和mvvm ...

  6. “约见”面试官系列之常见面试题之第九十三篇之vue获取数据在哪个周期函数(建议收藏)

    然后必须知道一点,vue是数据驱动的(只关心data即可),换句话说,就是,只要我能操作到 data中的数据即可. 所以,根据上面的生命周期,其实你放到 mounted中完全可以,因为这个阶段data ...

  7. “约见”面试官系列之常见面试题之第九十二篇之created和mounted区别(建议收藏)

    beforeCreate 创建之前:已经完成了 初始化事件和生命周期 created 创建完成:已经完成了 初始化注册和响应 beforeMount 挂载之前:已经完成了模板渲染 mounted :挂 ...

  8. “约见”面试官系列之常见面试题之第九十一篇之简述Vue的生命周期适用于哪些场景(建议收藏)

    答:beforeCreate:在new一个vue实例后,只有一些默认的生命周期钩子和默认事件,其他的东西都还没创建.在beforeCreate生命周期执行的时候,data和methods中的数据都还没 ...

  9. “约见”面试官系列之常见面试题之第九十篇之页面加载触发函数(建议收藏)

    第一次页面加载时会触发 beforeCreate, created, beforeMount, mounted 这几个钩子 本面试题为前端常考面试题,后续有机会继续完善.我是歌谣,一个沉迷于故事的讲述 ...

最新文章

  1. Docker源码分析(六):Docker Daemon网络
  2. JavaScript实现hornerMethod霍纳法算法(附完整源码)
  3. 【C++】 为什么C++空类占一个字节
  4. 包-封装模块、设置__init__和外界导入包
  5. CF1114F-Please, another Queries on Array?【线段树,欧拉函数】
  6. [转]android 获取 imei号码
  7. JavaScript 函数定义+内置函数使用+array对象+object类型
  8. percona zabbix mysql_zabbix采用percona监控mysql主从
  9. 计算机与体育教育的关系,试论现代信息技术与体育教育的关系论文.doc
  10. 红米note 4x Android 8,红米note 4X升级安卓7.0:MIUI8提前公测
  11. 数据库之战 | 寻找你心中的数据库漫威英雄
  12. 微博改变一切_改变自己是神,改变别人是神经病!(深度好文)
  13. 【华人学者风采】陈积明 浙江大学
  14. 十、RabbitMQ发布确认高级
  15. 小米品牌升级,启用新LOGO
  16. Nmap命令详解(全)
  17. win10系统能正常接收qq微信但打不开网页问题解决方法
  18. 【自动化测试】Pytest+Appium+Allure 做 UI 自动化的那些事
  19. Hyperledger Fabric 1.0 快速搭建 -------- 多机部署 Fabric CA节点服务
  20. 用php写圣诞祝福页面,2018最美的圣诞节祝福网页【圣诞节祝福语_圣诞节祝福短信】...

热门文章

  1. 4-1 线程安全性-原子性-atomic-1
  2. 【SqlServer】Sqlserver中的DOS命令操作
  3. scrapy之内蒙古自治区环境保护厅
  4. TCP协议的三次握手和四次分手
  5. Centos7完全分布式搭建Hadoop2.7.3
  6. iOS UI-常用控件
  7. 提示以下的错误信息:“未能在设计视图中打开, 块中,以不同方式将值括起来 ”...
  8. 中南大学 oracle试卷,数据库原理期末复习(中南大学)数据库原理、技术及应用2.ppt...
  9. Javascript 函数详解
  10. 我的新书《PWA入门与实践》上市了