Vue中避免濫用this去讀取data中數(shù)據(jù)
前言
在Vue中,data選項(xiàng)是個(gè)好東西,把數(shù)據(jù)往里一丟,在一個(gè)Vue組件中任何一個(gè)地方都可以通過(guò)this來(lái)讀取data中數(shù)據(jù)。但是要避免濫用this去讀取data中數(shù)據(jù),至于在哪里要避免濫用,如果濫用會(huì)導(dǎo)致什么后果,本專(zhuān)欄將會(huì)一一揭曉。
一、用this讀取data中數(shù)據(jù)的過(guò)程
在Vue源碼中會(huì)把data中數(shù)據(jù)添加getter函數(shù)和setter函數(shù),將其轉(zhuǎn)成響應(yīng)式的。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ù)時(shí),會(huì)觸發(fā)getter函數(shù),在其中通過(guò) var value = getter ? getter.call(obj) : val;
獲取到值后執(zhí)行 return value
,實(shí)現(xiàn)讀取數(shù)據(jù)的目的。
這里可以得出一個(gè)結(jié)論,在Dep.target存在時(shí),使用this去讀取data中數(shù)據(jù)時(shí)會(huì)去收集依賴(lài)。如果濫用this去讀取data中數(shù)據(jù),會(huì)多次重復(fù)地收集依賴(lài),從而產(chǎn)生性能問(wèn)題。
二、Dep.target什么時(shí)候存在
Dep.target是由依賴(lài)賦值的。依賴(lài)又稱(chēng)為Watcher(偵聽(tīng)者)或者訂閱者。在Vue中有三種依賴(lài),其中兩種是很常見(jiàn)的,就是watch(偵聽(tīng)器)和computed(計(jì)算屬性)。還有一種隱藏的依賴(lài)———渲染W(wǎng)atcher,在模板首次渲染的過(guò)程中創(chuàng)建的。
Dep.target是在依賴(lài)創(chuàng)建時(shí)被賦值,依賴(lài)是用構(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最后會(huì)執(zhí)行實(shí)例方法get
,在實(shí)例方法get
中執(zhí)行pushTarget(this)
中給Dep.target賦值的。
而依賴(lài)是在Vue頁(yè)面或組件初次渲染時(shí)創(chuàng)建,所以產(chǎn)生的性能問(wèn)題應(yīng)該是首次渲染過(guò)慢的問(wèn)題。
三、在何處濫用this去讀取data中數(shù)據(jù)
在Dep.target存在時(shí)去執(zhí)行這些濫用this去讀取data中數(shù)據(jù)的代碼會(huì)產(chǎn)生性能問(wèn)題,故還要搞清楚這些代碼是寫(xiě)在哪里才會(huì)被執(zhí)行到,換句話(huà)來(lái)說(shuō),要搞清楚在哪里濫用this去讀取data中數(shù)據(jù)會(huì)產(chǎn)生性能問(wèn)題。
在第二小節(jié)中介紹了Dep.target被賦值后會(huì)執(zhí)行value = this.getter.call(vm, vm)
,其中this.getter
是一個(gè)函數(shù),那么若在其中有用this去讀取data數(shù)據(jù),就會(huì)去收集依賴(lài),假如濫用的話(huà)就會(huì)產(chǎn)生性能問(wèn)題。
this.getter
是在創(chuàng)建依賴(lài)過(guò)程中賦值的,每種依賴(lài)的this.getter
都是不相同的。下面來(lái)一一介紹。
- watch(偵聽(tīng)器)依賴(lài)的
this.getter
是parsePath
函數(shù),其函數(shù)參數(shù)就是偵聽(tīng)的對(duì)象。
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 } }
如下所示的代碼中的 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è)過(guò)程中不會(huì)存在濫用this去讀取data中數(shù)據(jù)的場(chǎng)景。
watch:{ a:function(newVal, oldVal){ //做點(diǎn)什么 } } vm.$watch('a.b.c', function (newVal, oldVal) { // 做點(diǎn)什么 })
- computed(計(jì)算屬性)依賴(lài)的
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è)例子,代碼如下所示。
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; } }
在計(jì)算屬性d中就存在濫用this去讀取data數(shù)據(jù)。其中this.a
是個(gè)數(shù)組,此時(shí)Dep.target的值為計(jì)算屬性d這個(gè)依賴(lài),在循環(huán)this.a
中使用this去獲取中a、b、c、e、f的數(shù)據(jù),使這些數(shù)據(jù)進(jìn)行一系列復(fù)雜的邏輯運(yùn)算來(lái)重復(fù)地收集計(jì)算屬性d這個(gè)依賴(lài)。導(dǎo)致獲取計(jì)算屬性d的值的速度變慢,從而產(chǎn)生性能問(wèn)題。
- 渲染W(wǎng)atcher的
this.getter
是一個(gè)函數(shù)如下所示:
updateComponent = function() { vm._update(vm._render(), hydrating); };
其中vm._render()
會(huì)把template模板生成的渲染函數(shù)render轉(zhuǎn)成虛擬DOM(VNode):vnode = render.call(vm._renderProxy, vm.$createElement);
,舉一個(gè)例子來(lái)說(shuō)明一下渲染函數(shù)render是什么。
例如template模板:
<template> <div class="wrap"> <p>{{a}}<span>{}</span></p> </div> </template>
通過(guò)vue-loader會(huì)生成渲染函數(shù)render,如下所示:
(function anonymous() { with(this) { return _c('div', { attrs: { "class": "wrap" } }, [_c('p', [_v(_s(a)), _c('span', [_v(_s(b))])])]) } })
其中with語(yǔ)句的作用是為一個(gè)或一組語(yǔ)句指定默認(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è)例子,代碼如下所示:
<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ù)組過(guò)程中,不斷用this去讀取data中arr、obj的數(shù)據(jù),使這些數(shù)據(jù)進(jìn)行一系列復(fù)雜的邏輯運(yùn)算來(lái)重復(fù)收集這個(gè)依賴(lài),導(dǎo)致初次渲染的速度變慢,從而產(chǎn)生性能問(wèn)題。
四、如何避免濫用this去讀取data中數(shù)據(jù)
綜上所述在計(jì)算屬性和template模板中濫用this去讀取data中數(shù)據(jù)會(huì)導(dǎo)致多次重復(fù)地收集依賴(lài),從而產(chǎn)生性能問(wèn)題,那要怎么避免這種情況。
- 計(jì)算屬性中如何避免
用ES6對(duì)象解構(gòu)賦值來(lái)避免,計(jì)算屬性的值是一個(gè)函數(shù),其參數(shù)是Vue的實(shí)例化this對(duì)象,在上述計(jì)算屬性中濫用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、b、c、e、f賦值給對(duì)應(yīng)的變量a、b、c、e、f,然后在計(jì)算屬性中可以通過(guò)這些變量訪問(wèn)data數(shù)據(jù)的,且不會(huì)觸發(fā)data中對(duì)應(yīng)數(shù)據(jù)的依賴(lài)收集。這樣只用this讀取了一次data中的數(shù)據(jù),只觸發(fā)了一次依賴(lài)收集,避免了多次重復(fù)地依賴(lài)收集產(chǎn)生的性能問(wèn)題。
- template模板中如何避免
提前處理v-for循環(huán)所用的數(shù)據(jù),不要在v-for循環(huán)中去讀取數(shù)組、對(duì)象類(lèi)型的數(shù)據(jù)。在上述template模板中濫用this的例子中可以這樣優(yōu)化。
假設(shè)list、arr、obj皆是服務(wù)端返回來(lái)的數(shù)據(jù),且arr和obj沒(méi)有用到任何模塊渲染中,可以這樣優(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> const arr = []; const obj = {} export default { data() { return { list: [], } }, computed: { listData: function ({list}) { list.forEach(item => { item.name = arr[item.index].name; item.age = obj[item.id].age; }) return list; } }, } </script>
以上就是Vue中避免濫用this去讀取data中數(shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于Vue中避免濫用this的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Vue2.0/3.0雙向數(shù)據(jù)綁定的實(shí)現(xiàn)原理詳解
- 關(guān)于vuex強(qiáng)刷數(shù)據(jù)丟失問(wèn)題解析
- Vue 如何追蹤數(shù)據(jù)變化
- vue+canvas實(shí)現(xiàn)數(shù)據(jù)實(shí)時(shí)從上到下刷新瀑布圖效果(類(lèi)似QT的)
- vue 數(shù)據(jù)(data)賦值問(wèn)題的解決方案
- Vue 重置data的數(shù)據(jù)為初始狀態(tài)操作
- Vue組件傳值過(guò)程中丟失數(shù)據(jù)的分析與解決方案
- SpringBoot+Vue實(shí)現(xiàn)數(shù)據(jù)添加功能
- 手寫(xiě)Vue2.0 數(shù)據(jù)劫持的示例
- vue 數(shù)據(jù)雙向綁定的實(shí)現(xiàn)方法
- 用vue設(shè)計(jì)一個(gè)數(shù)據(jù)采集器
相關(guān)文章
vuex項(xiàng)目中登錄狀態(tài)管理的實(shí)踐過(guò)程
由于狀態(tài)零散地分布在許多組件和組件之間的交互中,大型應(yīng)用復(fù)雜度也經(jīng)常逐漸增長(zhǎng),為了解決這個(gè)問(wèn)題,Vue 提供 vuex,這篇文章主要給大家介紹了關(guān)于vuex項(xiàng)目中登錄狀態(tài)管理的相關(guān)資料,需要的朋友可以參考下2021-09-09vue2的todolist入門(mén)小項(xiàng)目的詳細(xì)解析
本篇文章主要介紹了vue2的todolist入門(mén)小項(xiàng)目的詳細(xì)解析,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05vue3實(shí)現(xiàn)在新標(biāo)簽中打開(kāi)指定網(wǎng)址的方法
我希望點(diǎn)擊查看按鈕的時(shí)候,能夠在新的標(biāo)簽頁(yè)面打開(kāi)這個(gè)文件的地址進(jìn)行預(yù)覽,該如何實(shí)現(xiàn)呢,下面小編給大家?guī)?lái)了基于vue3實(shí)現(xiàn)在新標(biāo)簽中打開(kāi)指定的網(wǎng)址,感興趣的朋友跟隨小編一起看看吧2024-07-07解決vue中監(jiān)聽(tīng)input只能輸入數(shù)字及英文或者其他情況的問(wèn)題
今天小編就為大家分享一篇解決vue中監(jiān)聽(tīng)input只能輸入數(shù)字及英文或者其他情況的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Vue頁(yè)面中實(shí)現(xiàn)平滑滾動(dòng)功能
這是一個(gè)實(shí)現(xiàn)平滑滾動(dòng)的函數(shù),可以讓頁(yè)面在滾動(dòng)到指定位置時(shí)產(chǎn)生緩動(dòng)效果,本文給大家介紹了如何在在Vue頁(yè)面中實(shí)現(xiàn)平滑滾動(dòng)功能,<BR>,文中詳細(xì)的代碼講解供大家參考,具有一定的參考價(jià)值,需要的朋友可以參考下2023-12-12