一、前言
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: '#test', data: { name: 'Monkey' } }); </script> </body> </html>
当我们在chrome控制台,更改vm.name时,页面中的数据也随之改变,但我们并没有与DOM直接接触
好了,今儿的核心就是模拟上述Demo中的数据驱动。
二、模拟Vue之数据驱动
通过粗浅地走读Vue的源码,发现达到这一效果的核心思路其实就是利用ES5的defineProperty方法,监听data数据,如果数据改变,那么就对页面做相关操作。
有了大体思路,那么我们就开始一步一步实现一个简易版的Vue数据驱动吧,简称SimpleVue。
Vue实例的创建过程,如下:
var vm = new Vue({ el: '#test', data: { name: 'Monkey' } });
因此,我们也依瓢画葫芦,构建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 = ''; result = template.replace(reg, function(rs, $1, $2){ var val = that[$2] || ''; return $1 + val; }); this.$el.innerHTML = result; console.log('updated'); } };
好了,整合上述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 = ''; result = template.replace(reg, function(rs, $1, $2){ var val = that[$2] || ''; return $1 + val; }); this.$el.innerHTML = result; console.log('updated'); } };
测试代码如下:
<!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: '#test', data: { name: 'Monkey' } }); </script> </body> </html>
效果如下:
三、优化
上述实现效果,还不错哦。
但是,我们走读下上述代码,感觉还可以优化下。
(1)、在watchData方法中监听每个data属性时,如果我们设置相同值,页面也会更新的,因为set是监听赋值的,它又不知道是不是同一个值,因此,优化如下:
(2)、在上述基础,我们加入了新旧值判断,但是如果我们频繁更新data属性呢?那么也就会频繁调用update方法。例如,当我们给vm.name同时赋值两个值时,页面就会更新两次,如下:
怎么解决呢?
利用节流,即可:
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 = ''; result = template.replace(reg, function(rs, $1, $2){ var val = that[$2] || ''; return $1 + val; }); this.$el.innerHTML = result; console.log('updated'); } };
且,为了让我们使用更加方便,我们可以在上述代码基础上,加入一个created钩子(当然,你可以加入更多),完整代码见github。
好了,简单的数据驱动,我们算 实现了,也优化了,但,其实上述简易版Vue有很多问题,例如:
1)、监听的属性是个对象呢?且对象里又有其他属性,不就监听不成功了么?如下:
2)、通过上述1)介绍,如果监听的属性是个对象,那么又该如何渲染DOM呢?
3)、渲染DOM我们采用的是innerHTML,那么随着DOM的扩大,性能显而易见,又该如何解决?
等等问题,我们将在后续随笔通过精读源码,一步一步完善。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
更多Vue data-driven simulation implementation 1相关文章请关注PHP中文网!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
