<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【Vuejs】Vuejs 中避免濫用 this 讀取 data 中數(shù)據(jù)

          共 11334字,需瀏覽 23分鐘

           ·

          2021-07-10 00:22


          作者:紅塵煉心

          https://juejin.cn/post/6934911314871451685

          前言

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

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

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

          function reactiveGetter() {
              var value = getter ? getter.call(obj) : val;
              if (Dep.target) {
                  dep.depend();
                  if (childOb) {
                      childOb.dep.depend();
                      if (Array.isArray(value)) {
                          dependArray(value);
                      }
                  }
              }
              return value
          }

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

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

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

          二、Dep.target什么時候存在

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

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

          function Watcher(vm, expOrFn, cb, options, isRenderWatcher) {
              //...
              if (typeof expOrFn === 'function') {
                  this.getter = expOrFn;
              } else {
                  this.getter = parsePath(expOrFn);
              }
              this.value = this.lazy ? undefined : this.get();
          };
          Watcher.prototype.get = function get() {
              pushTarget(this);
              try {
                  value = this.getter.call(vm, vm);
              } catch (e) {
                  
              }
              return value
          };
          Dep.target = null;
          var targetStack = [];
          function pushTarget(target) {
              targetStack.push(target);
              Dep.target = target;
          }

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

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

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

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

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

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

          • watch(偵聽器)依賴的this.getterparsePath函數(shù),其函數(shù)參數(shù)就是偵聽的對象。

            var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]"));
            function parsePath(path) {
              if (bailRE.test(path)) {
                  return
              }
              var segments = path.split('.');
              return function(obj) {
                  for (var i = 0; i < segments.length; i++) {
                      if (!obj) {
                          return
                      }
                      obj = obj[segments[i]];
                  }
                  return obj
              }
            }

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

            watch:{
            a:function(newVal, oldVal){
              //做點什么
            }
            }
            vm.$watch('a.b.c'function (newVal, oldVal) {
            // 做點什么
            })
          • computed(計算屬性)依賴的this.getter有兩種,如果計算屬性的值是個函數(shù),那么this.getter就是這個函數(shù)。如果計算屬性的值是個對象,那么this.getter就是這個對象的get屬性值,get屬性值也是個函數(shù)。在這個函數(shù)可能會存在濫用this去讀取data中數(shù)據(jù)的場景,舉個例子,代碼如下所示。

            computed:{
              d:function(){
                  let result = 0;
                  for(let key in this.a){
                      if(this.a[key].num > 20){
                          result += this.a[key].num + this.b + this.c;
                      }else{
                          result += this.a[key].num + this.e + this.f;
                      }
                  }
                  return result;
              }
            }

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

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

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

          例如template模板:

          <template>
            <div class="wrap">
              <p>{{a}}<span>{}</span></p>
            </div>
          </template>

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

          (function anonymous() {
              with(this) {
                  return _c('div', {
                      attrs: {
                          "class""wrap"
                      }
                  }, [_c('p', [_v(_s(a)), _c('span', [_v(_s(b))])])])
              }
          })

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

          <template>
            <div class="wrap">
              <div v-for=item in list>
                <div> {{ arr[item.index]['name'] }} </div>
                <div> {{ obj[item.id]['age'] }} </div>
              </div>
            </div>
          </template>

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

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

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

          • 計算屬性中如何避免

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

          優(yōu)化前:

          computed:{
              d:function(){
                  let result = 0;
                  for(let key in this.a){
                      if(this.a[key].num > 20){
                          result += this.a[key].num + this.b + this.c;
                      }else{
                          result += this.a[key].num + this.e + this.f;
                      }
                  }
                  return result;
              }
          }

          優(yōu)化后:

          computed: {
            d({ a, b, c, e, f }) {
              let result = 0;
              for (let key in a) {
                if (a[key].num > 20) {
                  result += a[key].num + b + c;
                } else {
                  result += a[key].num + e + f;
                }
              }
              return result;
            }
          }

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

          • template模板中如何避免

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

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

          優(yōu)化前:

          <template>
            <div class="wrap">
              <div v-for=item in list>
                <div> {{ arr[item.index]['name'] }} </div>
                <div> {{ obj[item.id]['age'] }} </div>
              </div>
            </div>
          </template>

          優(yōu)化后:

          <template>
            <div class="wrap">
              <div v-for=item in listData>
                <div{{item.name}} </div>
                  <div>{{item.age}}</div>
              </div>
            </div>
          </template>
          <script>
          export default {
            data() {
              return {
                list: [],
              }
            },
            created(){
              // 在這里定義arr和obj避免被轉(zhuǎn)成響應式
              this.arr = [];
              this.obj = {};
            },
            computed: {
              listData: function ({list}) {
                list.forEach(item => {
                  item.name = this.arr[item.index].name;
                  item.age = this.obj[item.id].age;
                })
                return list;
              }
            },
          }
          </script>

          1. JavaScript 重溫系列(22篇全)
          2. ECMAScript 重溫系列(10篇全)
          3. JavaScript設計模式 重溫系列(9篇全)
          4. 正則 / 框架 / 算法等 重溫系列(16篇全)
          5. Webpack4 入門(上)|| Webpack4 入門(下)
          6. MobX 入門(上) ||  MobX 入門(下)
          7. 120+篇原創(chuàng)系列匯總

          回復“加群”與大佬們一起交流學習~

          點擊“閱讀原文”查看 120+ 篇原創(chuàng)文章

          瀏覽 29
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚洲色丁香 | 天天干天天想天天日天天日 天天 | 日韩一级片在现观看视频 | 国产高清第一页 | 激情开心五月天 |