溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

發(fā)布時間:2020-08-25 09:23:29 來源:腳本之家 閱讀:121 作者:猴子 欄目:web開發(fā)

一、前言

Vue有一核心就是數(shù)據(jù)驅(qū)動(Data Driven),允許我們采用簡潔的模板語法來聲明式的將數(shù)據(jù)渲染進DOM,且數(shù)據(jù)與DOM是綁定在一起的,這樣當我們改變Vue實例的數(shù)據(jù)時,對應的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時,頁面中的數(shù)據(jù)也隨之改變,但我們并沒有與DOM直接接觸,效果如下:

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

好了,今兒的核心就是模擬上述Demo中的數(shù)據(jù)驅(qū)動。

二、模擬Vue之數(shù)據(jù)驅(qū)動

通過粗淺地走讀Vue的源碼,發(fā)現(xiàn)達到這一效果的核心思路其實就是利用ES5的defineProperty方法,監(jiān)聽data數(shù)據(jù),如果數(shù)據(jù)改變,那么就對頁面做相關(guān)操作。

有了大體思路,那么我們就開始一步一步實現(xiàn)一個簡易版的Vue數(shù)據(jù)驅(qū)動吧,簡稱SimpleVue。

Vue實例的創(chuàng)建過程,如下:

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

因此,我們也依瓢畫葫蘆,構(gòu)建SimpleVue構(gòu)造函數(shù)如下:

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方法,監(jiān)聽data中的屬性,如果屬性值改變,那么我們就進行相關(guān)的頁面處理。

如下:

SimpleVue.prototype = {
 //監(jiān)聽data屬性
 watchData: function(){
  var data = this.$options.data,//得到data對象
   keys = Object.keys(data),//data對象上全部的自身屬性,返回數(shù)組
   that = this;
  keys.forEach(function(elem){//監(jiān)聽每個屬性
   Object.defineProperty(that, elem, {
    enumerable: true,
    configurable: true,
    get: function(){
     return that._data[elem];
    },
    set: function(newVal){
     that._data[elem] = newVal;
     that.update();//數(shù)據(jù)變化,更新頁面
    }
   });
   that[elem] = data[elem];//初次進入改變that[elem],從而觸發(fā)update方法
  });
 }
};

好了,如果我們檢測到數(shù)據(jù)變化了呢?

那么,我們就更新視圖嘛。

但是,怎么更新呢?

簡單的實現(xiàn)方式就是,在初次構(gòu)建SimpleVue實例時,就將頁面中的模板保存下來,每次實例數(shù)據(jù)一改變,就通過正則替換掉原始的模板,即雙括號中的變量,如下:

SimpleVue.prototype = {
 //初始化SimpleVue實例時,就將原始模板保留
 getTemplate: function(){
  this.template = this.$el.innerHTML; 
 },
 //數(shù)據(jù)改變更新視圖
 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; 
 },
 //監(jiān)聽data屬性
 watchData: function(){
  var data = this.$options.data,//得到data對象
   keys = Object.keys(data),//data對象上全部的自身屬性,返回數(shù)組
   that = this;
  keys.forEach(function(elem){//監(jiān)聽每個屬性
   Object.defineProperty(that, elem, {
    enumerable: true,
    configurable: true,
    get: function(){
     return that._data[elem];
    },
    set: function(newVal){
     that._data[elem] = newVal;
     that.update();//數(shù)據(jù)變化,更新頁面
    }
   });
   that[elem] = data[elem];
  });
 },
 //數(shù)據(jù)改變更新視圖
 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>

效果如下:

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

三、優(yōu)化

上述實現(xiàn)效果,還不錯哦。

但是,我們走讀下上述代碼,感覺還可以優(yōu)化下。

(1)、在watchData方法中監(jiān)聽每個data屬性時,如果我們設置相同值,頁面也會更新的,因為set是監(jiān)聽賦值的,它又不知道是不是同一個值,因此,優(yōu)化如下:

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

(2)、在上述基礎,我們加入了新舊值判斷,但是如果我們頻繁更新data屬性呢?那么也就會頻繁調(diào)用update方法。例如,當我們給vm.name同時賦值兩個值時,頁面就會更新兩次,如下:

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

怎么解決呢?

利用節(jié)流,即可:

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

好了,將優(yōu)化點整合到原有代碼中,得下:

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。

好了,簡單的數(shù)據(jù)驅(qū)動,我們算 實現(xiàn)了,也優(yōu)化了,但,其實上述簡易版Vue有很多問題,例如:

1)、監(jiān)聽的屬性是個對象呢?且對象里又有其他屬性,不就監(jiān)聽不成功了么?如下:

Vue數(shù)據(jù)驅(qū)動模擬實現(xiàn)1

2)、通過上述1)介紹,如果監(jiān)聽的屬性是個對象,那么又該如何渲染DOM呢?

3)、渲染DOM我們采用的是innerHTML,那么隨著DOM的擴大,性能顯而易見,又該如何解決?

等等問題,我們將在后續(xù)隨筆通過精讀源碼,一步一步完善。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI