自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

『前端優(yōu)化』—— Vue中避免濫用this去讀取data中數(shù)據(jù)

開發(fā) 前端
在Vue中,data選項(xiàng)是個(gè)好東西,把數(shù)據(jù)往里一丟,在一個(gè)Vue組件中任何一個(gè)地方都可以通過this來讀取data中數(shù)據(jù)。

[[390228]]

 前言

在Vue中,data選項(xiàng)是個(gè)好東西,把數(shù)據(jù)往里一丟,在一個(gè)Vue組件中任何一個(gè)地方都可以通過this來讀取data中數(shù)據(jù)。但是要避免濫用this去讀取data中數(shù)據(jù),至于在哪里要避免濫用,如果濫用會(huì)導(dǎo)致什么后果,本專欄將會(huì)一一揭曉。

一、用this讀取data中數(shù)據(jù)的過程

在Vue源碼中會(huì)把data中數(shù)據(jù)添加getter函數(shù)和setter函數(shù),將其轉(zhuǎn)成響應(yīng)式的。getter函數(shù)代碼如下所示: 

  1. function reactiveGetter() {  
  2.     var value = getter ? getter.call(obj) : val;  
  3.     if (Dep.target) {  
  4.         dep.depend();  
  5.         if (childOb) {  
  6.             childOb.dep.depend();  
  7.             if (Array.isArray(value)) {  
  8.                 dependArray(value);  
  9.             } 
  10.         }  
  11.     }  
  12.     return value  

用this讀取data中數(shù)據(jù)時(shí),會(huì)觸發(fā)getter函數(shù),在其中通過 var value = getter ? getter.call(obj) : val; 獲取到值后執(zhí)行 return value,實(shí)現(xiàn)讀取數(shù)據(jù)的目的。

但是在其間還有一段代碼,在這段代碼中會(huì)經(jīng)過一系列復(fù)雜的邏輯運(yùn)算來收集依賴。這里只要知道在Dep.target存在時(shí)才會(huì)去收集依賴。

    這里可以得出一個(gè)結(jié)論,在Dep.target存在時(shí),使用this去讀取data中數(shù)據(jù)時(shí)會(huì)去收集依賴。如果濫用this去讀取data中數(shù)據(jù),會(huì)多次重復(fù)地收集依賴,從而產(chǎn)生性能問題。

二、Dep.target什么時(shí)候存在

Dep.target是由依賴賦值的。依賴又稱為Watcher(偵聽者)或者訂閱者。在Vue中有三種依賴,其中兩種是很常見的,就是watch(偵聽器)和computed(計(jì)算屬性)。還有一種隱藏的依賴———渲染W(wǎng)atcher,在模板首次渲染的過程中創(chuàng)建的。

Dep.target是在依賴創(chuàng)建時(shí)被賦值,依賴是用構(gòu)造函數(shù)Watcher創(chuàng)建。 

  1. lue = this.lazy ? undefined : this.get();  
  2. };  
  3. Watcher.prototype.get = function get() {  
  4.     pushTarget(this);  
  5.     try {  
  6.         value = this.getter.call(vm, vm);  
  7.     } catch (e) {        
  8.     }function Watcher(vm, expOrFn, cb, options, isRenderWatcher) {  
  9.     //...  
  10.     if (typeof expOrFn === 'function') {  
  11.         this.getter = expOrFn 
  12.     } else {  
  13.         this.getter = parsePath(expOrFn);  
  14.     }  
  15.     this.va  
  16.     return value  
  17. };  
  18. Dep.target = null 
  19. var targetStack = [];  
  20. function pushTarget(target) {  
  21.     targetStack.push(target);  
  22.     Dep.target = target;  

在構(gòu)造函數(shù)Watcher最后會(huì)執(zhí)行實(shí)例方法get,在實(shí)例方法get中執(zhí)行pushTarget(this)中給Dep.target賦值的。

而依賴是在Vue頁面或組件初次渲染時(shí)創(chuàng)建,所以產(chǎn)生的性能問題應(yīng)該是首次渲染過慢的問題。

三、在何處濫用this去讀取data中數(shù)據(jù)

在Dep.target存在時(shí)去執(zhí)行這些濫用this去讀取data中數(shù)據(jù)的代碼會(huì)產(chǎn)生性能問題,故還要搞清楚這些代碼是寫在哪里才會(huì)被執(zhí)行到,換句話來說,要搞清楚在哪里濫用this去讀取data中數(shù)據(jù)會(huì)產(chǎn)生性能問題。

在第二小節(jié)中介紹了Dep.target被賦值后會(huì)執(zhí)行value = this.getter.call(vm, vm),其中this.getter是一個(gè)函數(shù),那么若在其中有用this去讀取data數(shù)據(jù),就會(huì)去收集依賴,假如濫用的話就會(huì)產(chǎn)生性能問題。

this.getter是在創(chuàng)建依賴過程中賦值的,每種依賴的this.getter都是不相同的。下面來一一介紹。

  •  watch(偵聽器)依賴的this.getter是parsePath函數(shù),其函數(shù)參數(shù)就是偵聽的對(duì)象。 
  1. var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]"));  
  2. function parsePath(path) {  
  3.   if (bailRE.test(path)) {  
  4.       return  
  5.   }  
  6.   var segments = path.split('.');  
  7.   return function(obj) {  
  8.       for (var i = 0; i < segments.length; i++) {  
  9.           if (!obj) {  
  10.               return  
  11.           } 
  12.           objobj = obj[segments[i]];  
  13.       }  
  14.       return obj  
  15.   }  

如下所示的代碼中的 a 和 a.b.c作為參數(shù)傳入parsePath函數(shù)會(huì)返回一個(gè)函數(shù)賦值給this.getter,執(zhí)行this.getter.call(vm, vm)會(huì)得到this.a和this.a.b.c的值。在這個(gè)過程中不會(huì)存在濫用this去讀取data中數(shù)據(jù)的場(chǎng)景。   

  1. watch:{  
  2.    a:function(newVal, oldVal){  
  3.      //做點(diǎn)什么 
  4.    }  
  5.    }  
  6.    vm.$watch('a.b.c', function (newVal, oldVal) {  
  7.    // 做點(diǎn)什么  
  8.    }) 
  •  computed(計(jì)算屬性)依賴的this.getter有兩種,如果計(jì)算屬性的值是個(gè)函數(shù),那么this.getter就是這個(gè)函數(shù)。如果計(jì)算屬性的值是個(gè)對(duì)象,那么this.getter就是這個(gè)對(duì)象的get屬性值,get屬性值也是個(gè)函數(shù)。在這個(gè)函數(shù)可能會(huì)存在濫用this去讀取data中數(shù)據(jù)的場(chǎng)景,舉個(gè)例子,代碼如下所示。   
  1. computed:{  
  2.      d:function(){  
  3.          let result = 0 
  4.          for(let key in this.a){  
  5.              if(this.a[key].num > 20){  
  6.                  result += this.a[key].num + this.b + this.c;  
  7.              }else{  
  8.                  result += this.a[key].num + this.e + this.f;  
  9.              } 
  10.          }  
  11.          return result;  
  12.      }  
  13.    } 

在計(jì)算屬性d中就存在濫用this去讀取data數(shù)據(jù)。其中this.a是個(gè)數(shù)組,此時(shí)Dep.target的值為計(jì)算屬性d這個(gè)依賴,在循環(huán)this.a中使用this去獲取中a、b、c、e、f的數(shù)據(jù),使這些數(shù)據(jù)進(jìn)行一系列復(fù)雜的邏輯運(yùn)算來重復(fù)地收集計(jì)算屬性d這個(gè)依賴。導(dǎo)致獲取計(jì)算屬性d的值的速度變慢,從而產(chǎn)生性能問題。

  •   渲染W(wǎng)atcher的this.getter是一個(gè)函數(shù)如下所示: 
  1. updateComponent = function() {  
  2.   vm._update(vm._render(), hydrating);  
  3. }; 

其中vm._render()會(huì)把template模板生成的渲染函數(shù)render轉(zhuǎn)成虛擬DOM(VNode):vnode = render.call(vm._renderProxy, vm.$createElement);,舉一個(gè)例子來說明一下渲染函數(shù)render是什么。

例如template模板: 

  1. <template>  
  2.   <div class="wrap">  
  3.     <p>{{a}}<span>{}</span></p>  
  4.   </div>  
  5. </template> 

通過vue-loader會(huì)生成渲染函數(shù)render,如下所示: 

  1. (function anonymous() {  
  2.     with(this) {  
  3.         return _c('div', {  
  4.             attrs: {  
  5.                 "class": "wrap"  
  6.             }  
  7.         }, [_c('p', [_v(_s(a)), _c('span', [_v(_s(b))])])])  
  8.     }  
  9. }) 

其中with語句的作用是為一個(gè)或一組語句指定默認(rèn)對(duì)象,例with(this){ a + b } 等同 this.a + this.b,那么在template模板中使用{{ a }}相當(dāng)使用this去讀取data中的a數(shù)據(jù)。故在template模板生成的渲染函數(shù)render中也可能存在濫用this去讀取data中數(shù)據(jù)的場(chǎng)景。舉個(gè)例子,代碼如下所示: 

  1. <template>  
  2.   <div class="wrap">  
  3.     <div v-for=item in list>  
  4.       <div> {{ arr[item.index]['name'] }} </div>  
  5.       <div> {{ obj[item.id]['age'] }} </div>  
  6.     </div>  
  7.   </div>  
  8. </template> 

其中用v-for循環(huán)list數(shù)組過程中,不斷用this去讀取data中arr、obj的數(shù)據(jù),使這些數(shù)據(jù)進(jìn)行一系列復(fù)雜的邏輯運(yùn)算來重復(fù)收集這個(gè)依賴,導(dǎo)致初次渲染的速度變慢,從而產(chǎn)生性能問題。

四、如何避免濫用this去讀取data中數(shù)據(jù)

綜上所述在計(jì)算屬性和template模板中濫用this去讀取data中數(shù)據(jù)會(huì)導(dǎo)致多次重復(fù)地收集依賴,從而產(chǎn)生性能問題,那要怎么避免這種情況。

  •  計(jì)算屬性中如何避免

用ES6對(duì)象解構(gòu)賦值來避免,計(jì)算屬性的值是一個(gè)函數(shù),其參數(shù)是Vue的實(shí)例化this對(duì)象,在上述計(jì)算屬性中濫用this的例子中可以這樣優(yōu)化。

優(yōu)化前: 

  1. computed:{  
  2.     d:function(){  
  3.         let result = 0 
  4.         for(let key in this.a){  
  5.             if(this.a[key].num > 20){  
  6.                 result += this.a[key].num + this.b + this.c;  
  7.             }else{  
  8.                 result += this.a[key].num + this.e + this.f;  
  9.             }  
  10.         }  
  11.         return result;  
  12.     }  

優(yōu)化后: 

  1. computed: {  
  2.   d({ a, b, c, e, f }) {  
  3.     let result = 0 
  4.     for (let key in a) {  
  5.       if (a[key].num > 20) {  
  6.         result += a[key].num + b + c;  
  7.       } else {  
  8.         result += a[key].num + e + f;  
  9.       }  
  10.     }  
  11.     return result;  
  12.   }  

以上利用解構(gòu)賦值提前把data數(shù)據(jù)中的a、b、c、e、f賦值給對(duì)應(yīng)的變量a、b、c、e、f,然后在計(jì)算屬性中可以通過這些變量訪問data數(shù)據(jù)的,且不會(huì)觸發(fā)data中對(duì)應(yīng)數(shù)據(jù)的依賴收集。這樣只用this讀取了一次data中的數(shù)據(jù),只觸發(fā)了一次依賴收集,避免了多次重復(fù)地依賴收集產(chǎn)生的性能問題。

  •  template模板中如何避免

提前處理v-for循環(huán)所用的數(shù)據(jù),不要在v-for循環(huán)中去讀取數(shù)組、對(duì)象類型的數(shù)據(jù)。在上述template模板中濫用this的例子中可以這樣優(yōu)化。

假設(shè)list、arr、obj皆是服務(wù)端返回來的數(shù)據(jù),且arr和obj沒有用到任何模塊渲染中,可以這樣優(yōu)化。

優(yōu)化前: 

  1. <template>  
  2.   <div class="wrap">  
  3.     <div v-for=item in list>  
  4.       <div> {{ arr[item.index]['name'] }} </div>  
  5.       <div> {{ obj[item.id]['age'] }} </div>  
  6.     </div>  
  7.   </div>  
  8. </template> 

優(yōu)化后: 

  1. <template>  
  2.   <div class="wrap">  
  3.     <div v-for=item in listData>  
  4.       <div{{item.name}} </div>  
  5.         <div>{{item.age}}</div>  
  6.     </div>  
  7.   </div>  
  8. </template>  
  9. <script>  
  10. export default {  
  11.   data() {  
  12.     return {  
  13.       list: [],  
  14.     }  
  15.   },  
  16.   created(){  
  17.     // 在這里定義arr和obj避免被轉(zhuǎn)成響應(yīng)式  
  18.     this.arr = [];  
  19.     this.obj = {};  
  20.   }, 
  21.   computed: {  
  22.     listData: function ({list}) {  
  23.       list.forEach(item => {  
  24.         item.name = this.arr[item.index].name;  
  25.         item.age = this.obj[item.id].age;  
  26.       })  
  27.       return list;  
  28.     }  
  29.   },  
  30.  
  31. </script>  

 

責(zé)任編輯:龐桂玉 來源: 前端大全
相關(guān)推薦

2021-02-02 13:45:31

Vue代碼前端

2025-02-17 06:00:00

Task.Run.NET開發(fā)

2009-06-03 10:49:48

Hibernate事務(wù)

2020-04-30 08:22:52

try...excepPython代碼

2018-06-06 14:15:12

2025-01-22 07:59:59

2022-06-02 16:28:11

Telegram網(wǎng)絡(luò)釣魚帳戶

2011-06-20 14:44:49

網(wǎng)站優(yōu)化

2016-09-14 22:22:03

Android Vue性能優(yōu)化

2010-07-06 09:44:51

SQL Server數(shù)

2009-08-11 14:51:47

C#讀取Excel中數(shù)

2020-10-06 18:57:14

PostgreSQL數(shù)據(jù)庫數(shù)據(jù)導(dǎo)入

2020-08-20 08:23:52

VueDOM運(yùn)算符

2020-04-14 15:20:18

JSIF代碼

2021-10-09 23:33:55

監(jiān)控

2022-01-18 10:15:18

Vue性能優(yōu)化前端

2016-08-05 16:13:50

Android性能優(yōu)化對(duì)象

2020-03-03 11:20:37

數(shù)據(jù)結(jié)構(gòu)Vue內(nèi)存

2020-08-10 08:30:35

Vue 數(shù)據(jù)插槽

2015-07-30 10:12:32

JavaNullAssert
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)