search
HomeWeb Front-endJS TutorialVue data-driven simulation implementation 1

一、前言

Vue有一核心就是数据驱动(Data Driven),允许我们采用简洁的模板语法来声明式的将数据渲染进DOM,且数据与DOM是绑定在一起的,这样当我们改变Vue实例的数据时,对应的DOM元素也就会改变了。

如下:

<!DOCTYPE html>
<head>
 <meta charset="utf-8">
</head>
 <body>
  <div id="test">
   {{name}}
  </div>
  <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
  <script>
   var vm = new Vue({
    el: &#39;#test&#39;,
    data: {
     name: &#39;Monkey&#39;
    }
   });
  </script>  
 </body>
</html>

当我们在chrome控制台,更改vm.name时,页面中的数据也随之改变,但我们并没有与DOM直接接触

好了,今儿的核心就是模拟上述Demo中的数据驱动。

二、模拟Vue之数据驱动

通过粗浅地走读Vue的源码,发现达到这一效果的核心思路其实就是利用ES5的defineProperty方法,监听data数据,如果数据改变,那么就对页面做相关操作。

有了大体思路,那么我们就开始一步一步实现一个简易版的Vue数据驱动吧,简称SimpleVue。

Vue实例的创建过程,如下:

var vm = new Vue({
 el: &#39;#test&#39;,
 data: {
  name: &#39;Monkey&#39;
 }
});

因此,我们也依瓢画葫芦,构建SimpleVue构造函数如下:

function SimpleVue(obj){
 this.$el = document.querySelector(obj.el);
 this.$options = obj;
 this._data = Object.create(null);
 //入口
 this.init();
 obj = null;
};
SimpleVue.prototype = {
 constructor: SimpleVue,
 init: function(){
  //TODO
 }
};

接下来,我们在SimpleVue原型上编写一个watchData方法,通过利用ES5原生的defineProperty方法,监听data中的属性,如果属性值改变,那么我们就进行相关的页面处理。

如下:

SimpleVue.prototype = {
 //监听data属性
 watchData: function(){
  var data = this.$options.data,//得到data对象
   keys = Object.keys(data),//data对象上全部的自身属性,返回数组
   that = this;
  keys.forEach(function(elem){//监听每个属性
   Object.defineProperty(that, elem, {
    enumerable: true,
    configurable: true,
    get: function(){
     return that._data[elem];
    },
    set: function(newVal){
     that._data[elem] = newVal;
     that.update();//数据变化,更新页面
    }
   });
   that[elem] = data[elem];//初次进入改变that[elem],从而触发update方法
  });
 }
};

好了,如果我们检测到数据变化了呢?

那么,我们就更新视图嘛。

但是,怎么更新呢?

简单的实现方式就是,在初次构建SimpleVue实例时,就将页面中的模板保存下来,每次实例数据一改变,就通过正则替换掉原始的模板,即双括号中的变量,如下:

 SimpleVue.prototype = {
 //初始化SimpleVue实例时,就将原始模板保留
 getTemplate: function(){
  this.template = this.$el.innerHTML;
 },
 //数据改变更新视图
 update: function(){
  var that = this,
   template = that.template,
   reg = /(.*?)\{\{(\w*)\}\}/g,
   result = &#39;&#39;;
  result = template.replace(reg, function(rs, $1, $2){
   var val = that[$2] || &#39;&#39;;
   return $1 + val;
  });
  this.$el.innerHTML = result;
  console.log(&#39;updated&#39;);
 }
};


好了,整合上述js代码,完整的SimpleVue如下:

function SimpleVue(obj){
 this.$el = document.querySelector(obj.el);
 this.$options = obj;
 this._data = Object.create(null);
 //入口
 this.init();
 obj = null;
};
SimpleVue.prototype = {
 constructor: SimpleVue,
 init: function(){
  this.getTemplate();
  this.watchData();
 },
 //初始化SimpleVue实例时,就将原始模板保留
 getTemplate: function(){
  this.template = this.$el.innerHTML;
 },
 //监听data属性
 watchData: function(){
  var data = this.$options.data,//得到data对象
   keys = Object.keys(data),//data对象上全部的自身属性,返回数组
   that = this;
  keys.forEach(function(elem){//监听每个属性
   Object.defineProperty(that, elem, {
    enumerable: true,
    configurable: true,
    get: function(){
     return that._data[elem];
    },
    set: function(newVal){
     that._data[elem] = newVal;
     that.update();//数据变化,更新页面
    }
   });
   that[elem] = data[elem];
  });
 },
 //数据改变更新视图
 update: function(){
  var that = this,
   template = that.template,
   reg = /(.*?)\{\{(\w*)\}\}/g,
   result = &#39;&#39;;
  result = template.replace(reg, function(rs, $1, $2){
   var val = that[$2] || &#39;&#39;;
   return $1 + val;
  });
  this.$el.innerHTML = result;
  console.log(&#39;updated&#39;);
 }
};

   

测试代码如下:

<!DOCTYPE html>
<head>
 <meta charset="utf-8">
</head>
 <body>
  <div id="test">
   <div>{{name}}</div>
  </div>
  <script src="./SimpleVue.js"></script>
  <script>
   var vm = new SimpleVue({
    el: &#39;#test&#39;,
    data: {
     name: &#39;Monkey&#39;
    }
   });
  </script> 
 </body>
</html>

效果如下:

Vue data-driven simulation implementation 1

三、优化

上述实现效果,还不错哦。

但是,我们走读下上述代码,感觉还可以优化下。

(1)、在watchData方法中监听每个data属性时,如果我们设置相同值,页面也会更新的,因为set是监听赋值的,它又不知道是不是同一个值,因此,优化如下:

Vue data-driven simulation implementation 1

(2)、在上述基础,我们加入了新旧值判断,但是如果我们频繁更新data属性呢?那么也就会频繁调用update方法。例如,当我们给vm.name同时赋值两个值时,页面就会更新两次,如下:

Vue data-driven simulation implementation 1

怎么解决呢?

利用节流,即可:

SimpleVue.throttle = function(method, context, delay){
 clearTimeout(method.tId);
 method.tId = setTimeout(function(){
  method.call(context);
 }, delay);
};

好了,将优化点整合到原有代码中,得下:

function SimpleVue(obj){
 this.$el = document.querySelector(obj.el);
 this.$options = obj;
 this._data = Object.create(null);
 this.init();
 obj = null;
};
SimpleVue.throttle = function(method, context, delay){
 clearTimeout(method.tId);
 method.tId = setTimeout(function(){
  method.call(context);
 }, delay);
};
SimpleVue.prototype = {
 constructor: SimpleVue,
 init: function(){
  this.getTemplate();
  this.watchData();
 },
 getTemplate: function(){
  this.template = this.$el.innerHTML;
 },
 watchData: function(){
  var data = this.$options.data,
   keys = Object.keys(data),
   that = this;
  keys.forEach(function(elem){
   Object.defineProperty(that, elem, {
    enumerable: true,
    configurable: true,
    get: function(){
     return that._data[elem];
    },
    set: function(newVal){
     var oldVal = that[elem];
     if(oldVal === newVal){
      return;
     }
     that._data[elem] = newVal;
     SimpleVue.throttle(that.update, that, 50);
    }
   });
   that[elem] = data[elem];
  });
 },
 update: function(){
  var that = this,
   template = that.template,
   reg = /(.*?)\{\{(\w*)\}\}/g,
   result = &#39;&#39;;
  result = template.replace(reg, function(rs, $1, $2){
   var val = that[$2] || &#39;&#39;;
   return $1 + val;
  });
  this.$el.innerHTML = result;
  console.log(&#39;updated&#39;);
 }
};

且,为了让我们使用更加方便,我们可以在上述代码基础上,加入一个created钩子(当然,你可以加入更多),完整代码见github。

好了,简单的数据驱动,我们算 实现了,也优化了,但,其实上述简易版Vue有很多问题,例如:

1)、监听的属性是个对象呢?且对象里又有其他属性,不就监听不成功了么?如下:

Vue data-driven simulation implementation 1

2)、通过上述1)介绍,如果监听的属性是个对象,那么又该如何渲染DOM呢?

3)、渲染DOM我们采用的是innerHTML,那么随着DOM的扩大,性能显而易见,又该如何解决?

等等问题,我们将在后续随笔通过精读源码,一步一步完善。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多Vue data-driven simulation implementation 1相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function