淺談VUE防抖與節(jié)流的最佳解決方案(函數(shù)式組件)

2021-6-18    前端達人

這篇文章主要介紹了淺談VUE防抖與節(jié)流的最佳解決方案,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

有echarts使用經(jīng)驗的同學(xué)可能遇到過這樣的場景,在window.onresize事件回調(diào)里觸發(fā)echartsBox.resize()方法來達到重繪的目的,resize事件是連續(xù)觸發(fā)的這意味著echarts實例會連續(xù)的重繪這是非常耗性能的。還有一個常見的場景在input標(biāo)簽的input事件里請求后端接口,input事件也是連續(xù)觸發(fā)的,假設(shè)我輸入了“12”就會請求兩次接口參數(shù)分別是“1”和“12”,比浪費網(wǎng)絡(luò)資源更要命的是如果參數(shù)為“1”的請求返回數(shù)據(jù)的時間晚于參數(shù)為“12”的接口,那么我們得到的數(shù)據(jù)是和期望不符的。當(dāng)然基于axios可以做很多封裝可以取消上一個請求或者通過攔截做處理,但還是從防抖入手比較簡單。

防抖和節(jié)流到底是啥

函數(shù)防抖(debounce)

解釋:當(dāng)持續(xù)觸發(fā)某事件時,一定時間間隔內(nèi)沒有再觸發(fā)事件時,事件處理函數(shù)才會執(zhí)行一次,如果設(shè)定的時間間隔到來之前,又一次觸發(fā)了事件,就重新開始延時。

案例:持續(xù)觸發(fā)scroll事件時,并不立即執(zhí)行handle函數(shù),當(dāng)1000毫秒內(nèi)沒有觸發(fā)scroll事件時,才會延時觸發(fā)一次handle函數(shù)。

1
2
3
4
5
6
7
8
9
10
11
function debounce(fn, wait) {
 let timeout = null
 return function() {
  if(timeout !== null) clearTimeout(timeout)  
  timeout = setTimeout(fn, wait);
 }
}
function handle() { 
 console.log(Math.random())
}
window.addEventListener('scroll', debounce(handle, 1000))

addEventListener的第二個參數(shù)實際上是debounce函數(shù)里return回的方法,let timeout = null 這行代碼只在addEventListener的時候執(zhí)行了一次 觸發(fā)事件的時候不會執(zhí)行,那么每次觸發(fā)scroll事件的時候都會清除上次的延時器同時記錄一個新的延時器,當(dāng)scroll事件停止觸發(fā)后最后一次記錄的延時器不會被清除可以延時執(zhí)行,這是debounce函數(shù)的原理

函數(shù)節(jié)流(throttle)

解釋:當(dāng)持續(xù)觸發(fā)事件時,有規(guī)律的每隔一個時間間隔執(zhí)行一次事件處理函數(shù)。

案例:持續(xù)觸發(fā)scroll事件時,并不立即執(zhí)行handle函數(shù),每隔1000毫秒才會執(zhí)行一次handle函數(shù)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function throttle(fn, delay) {
 var prev = Date.now()    
 return function() {       
  var now = Date.now()       
  if (now - prev > delay) {         
   fn()       
   prev = Date.now()      
  }    
 }   
}   
function handle() {     
 console.log(Math.random())  
}
window.addEventListener('scroll', throttle(handle, 1000))

原理和防抖類似,每次執(zhí)行fn函數(shù)都會更新prev用來記錄本次執(zhí)行的時間,下一次事件觸發(fā)時判斷時間間隔是否到達預(yù)先的設(shè)定,重復(fù)上述操作。

防抖和節(jié)流都可以用于 mousemove、scroll、resize、input等事件,他們的區(qū)別在于防抖只會在連續(xù)的事件周期結(jié)束時執(zhí)行一次,而節(jié)流會在事件周期內(nèi)按間隔時間有規(guī)律的執(zhí)行多次。

在vue中的實踐

在vue中實現(xiàn)防抖無非下面這兩種方法

  • 封裝utils工具
  • 封裝組件

封裝utils工具

把上面的案例改造一下就能封裝一個簡單的utils工具

utils.js

1
2
3
4
5
6
let timeout = null
function debounce(fn, wait) {
 if(timeout !== null) clearTimeout(timeout)
 timeout = setTimeout(fn, wait)
}
export default debounce

app.js

1
2
3
4
5
6
7
8
9
10
11
12
<input type="text" @input="debounceInput($event)">
 
import debounce from './utils'
export default {
 methods: {
  debounceInput(E){
   debounce(() => {
    console.log(E.target.value)
   }, 1000)
  }
 }
}

封裝組件

至于組件的封裝我們要用到$listeners、$attrs這兩個屬性,他倆都是vue2.4新增的內(nèi)容,官網(wǎng)的介紹比較晦澀,我們來看他倆到底是干啥的:

$listeners: 父組件在綁定子組件的時候會在子組件上綁定很多屬性,然后在子組件里通過props注冊使用,那么沒有被props注冊的就會放在$listeners里,當(dāng)然不包括class和style,并且可以通過 v-bind="$attrs" 傳入子組件的內(nèi)部組件。

$listeners: 父組件在子組件上綁定的不含.native修飾器的事件會放在$listeners里,它可以通過 v-on="$listeners" 傳入內(nèi)部組件。

簡單來說$listeners、$attrs他倆是做屬性和事件的承接,這在對組件做二次封裝的時候非常有用。

我們以element-ui的el-input組件為例封裝一個帶防抖的debounce-input組件

debounce-input.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
 <el-input v-bind="$attrs" @input="debounceInput"/>
</template>
<script>
export default {
 data() {
  return {
   timeout: null
  }
 },
 methods: {
  debounceInput(value){
   if(this.timeout !== null) clearTimeout(this.timeout)  
   this.timeout = setTimeout(() => {
    this.$emit('input', value)
   }, 1000)
  }
 }
}
</script>

app.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
 <debounce-input placeholder="防抖" prefix-icon="el-icon-search" @input="inputEve"></debounce-input>
</template>
<script>
import debounceInput from './debounce-input'
export default {
 methods: {
  inputEve(value){
   console.log(value)
  }
 },
 components: {
  debounceInput
 }
}
</script>

上面組件的封裝用了$attrs,雖然不需要開發(fā)者關(guān)注屬性的傳遞,但是在使用上還是不方便的,因為把el-input封裝在了內(nèi)部這樣對樣式的限定也比較局限。有接觸過react高階組件的同學(xué)可能有了解,react高階組件本質(zhì)上是一個函數(shù)通過包裹被傳入的React組件,經(jīng)過一系列處理,最終返回一個相對增強的React組件。那么在vue中可以借鑒這種思路嗎,我們來了解一下vue的函數(shù)式組件。

關(guān)于vue函數(shù)式組件

什么是函數(shù)式組件?

函數(shù)式組件是指用一個Function來渲染一個vue組件,這個組件只接受一些 prop,我們可以將這類組件標(biāo)記為 functional,這意味著它無狀態(tài) (沒有響應(yīng)式數(shù)據(jù)),也沒有實例 (沒有this上下文)。

一個函數(shù)式組件大概向下面這樣:

1
2
3
4
5
6
7
8
9
10
export default () => {
 functional: true,
 props: {
  // Props 是可選的
 },
 // 為了彌補缺少的實例, 提供第二個參數(shù)作為上下文
 render: function (createElement, context) {
  return vNode
 }
}

注意:在 2.3.0 之前的版本中,如果一個函數(shù)式組件想要接收 prop,則 props 選項是必須的。在 2.3.0 或以上的版本中,你可以省略 props 選項,所有組件上的特性都會被自動隱式解析為 prop。但是你一旦注冊了 prop 那么只有被注冊的 prop 會出現(xiàn)在 context.prop 里。

render函數(shù)的第二個參數(shù)context用來代替上下文this他是一個包含如下字段的對象:

  • props:提供所有 prop 的對象
  • children: VNode 子節(jié)點的數(shù)組
  • slots: 一個函數(shù),返回了包含所有插槽的對象
  • scopedSlots: (2.6.0+) 一個暴露傳入的作用域插槽的對象。也以函數(shù)形式暴露普通插槽。
  • data:傳遞給組件的整個數(shù)據(jù)對象,作為 createElement 的第二個參數(shù)傳入組件
  • parent:對父組件的引用
  • listeners: (2.3.0+) 一個包含了所有父組件為當(dāng)前組件注冊的事件監(jiān)聽器的對象。這是 data.on 的一個別名。
  • injections: (2.3.0+) 如果使用了 inject 選項,則該對象包含了應(yīng)當(dāng)被注入的屬性。

vm.$slots API 里面是什么

slots用來訪問被插槽分發(fā)的內(nèi)容。每個具名插槽 有其相應(yīng)的屬性 (例如:v-slot:foo 中的內(nèi)容將會在 vm.$slots.foo 中被找到)。default 屬性包括了所有沒有被包含在具名插槽中的節(jié)點,或 v-slot:default 的內(nèi)容。

slots() 和 children 對比

你可能想知道為什么同時需要 slots() 和 children。slots().default 不是和 children 類似的嗎?在一些場景中,是這樣——但如果是如下的帶有子節(jié)點的函數(shù)式組件呢?

1
2
3
4
5
6
<my-functional-component>
 <p v-slot:foo>
  first
 </p>
 <p>second</p>
</my-functional-component>

對于這個組件,children 會給你兩個段落標(biāo)簽,而 slots().default 只會傳遞第二個匿名段落標(biāo)簽,slots().foo 會傳遞第一個具名段落標(biāo)簽。同時擁有 children 和 slots(),因此你可以選擇讓組件感知某個插槽機制,還是簡單地通過傳遞 children,移交給其它組件去處理。

一個函數(shù)式組件的使用場景

假設(shè)有一個a組件,引入了 a1,a2,a3 三個組件,a組件的父組件給a組件傳入了一個type屬性根據(jù)type的值a組件來決定顯示 a1,a2,a3 中的那個組件。這樣的場景a組件用函數(shù)式組件是非常方便的。那么為什么要用函數(shù)式組件呢?一句話:渲染開銷低,因為函數(shù)式組件只是函數(shù)。

用函數(shù)式組件的方式來實現(xiàn)防抖

因為業(yè)務(wù)關(guān)系該防抖組件的封裝同時支持 input、button、el-input、el-button 的使用,如果是input類組件對input事件做防抖處理,如果是button類組件對click事件做防抖處理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const debounce = (fun, delay = 500, before) => {
 let timer = null
 return (params) => {
  timer && window.clearTimeout(timer)
  before && before(params)
  timer = window.setTimeout(() => {
    // click事件fun是Function input事件fun是Array
   if (!Array.isArray(fun)) {
    fun = [fun]
   }
   for (let i in fun) {
    fun[i](params)
   }
   timer = null
  }, parseInt(delay))
 }
}
export default {
 name: 'Debounce',
 functional: true, // 靜態(tài)組件 當(dāng)不聲明functional時該組件同樣擁有上下文以及生命周期函數(shù)
 render(createElement, context) {
  const before = context.props.before
  const time = context.props.time
  const vnodeList = context.slots().default
  if (vnodeList === undefined){
   console.warn('<debounce> 組件必須要有子元素')
   return null
  }
  const vnode = vnodeList[0] || null // 獲取子元素虛擬dom
  if (vnode.tag === 'input') {
   const defaultFun = vnode.data.on.input
   const debounceFun = debounce(defaultFun, time, before) // 獲取節(jié)流函數(shù)
   vnode.data.on.input = debounceFun
  } else if (vnode.tag === 'button') {
   const defaultFun = vnode.data.on.click
   const debounceFun = debounce(defaultFun, time, before) // 獲取節(jié)流函數(shù)
   vnode.data.on.click = debounceFun
  } else if (vnode.componentOptions && vnode.componentOptions.tag === 'el-input') {
   const defaultFun = vnode.componentOptions.listeners.input
   const debounceFun = debounce(defaultFun, time, before) // 獲取節(jié)流函數(shù)
   vnode.componentOptions.listeners.input = debounceFun
  } else if (vnode.componentOptions && vnode.componentOptions.tag === 'el-button') {
   const defaultFun = vnode.componentOptions.listeners.click
   const debounceFun = debounce(defaultFun, time, before) // 獲取節(jié)流函數(shù)
   vnode.componentOptions.listeners.click = debounceFun
  } else {
   console.warn('<debounce> 組件內(nèi)只能出現(xiàn)下面組件的任意一個且唯一 el-button、el-input、button、input')
   return vnode
  }
  return vnode
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
 <debounce time="300" :before="beforeFun">
  <input type="text" v-model="inpModel" @input="inputChange"/>
 </debounce>
</template>
 
<script>
import debounce from './debounce'
export default {
 data() {
  return {
   inpModel: 1
  }
 },
 methods: {
  inputChange(e){
   console.log(e.target.value, '防抖')
  },
  beforeFun(e){
   console.log(e.target.value, '不防抖')
  }
 },
 components: {
  debounce
 }
}
</script>

原理也很簡單就是在vNode中攔截on下面的click、input事件做防抖處理,這樣在使用上就非常簡單了。

自定義指令 directive

我們來思考一個問題,函數(shù)式組件封裝防抖的關(guān)節(jié)是獲取vNode,那么我們通過自定義指令同樣可以拿到vNode,甚至還可以得到原生的Dom,這樣用自定義指令來處理會更加方便。。。。。。


藍藍設(shè)計建立了UI設(shè)計分享群,每天會分享國內(nèi)外的一些優(yōu)秀設(shè)計,如果有興趣的話,可以進入一起成長學(xué)習(xí),請掃碼藍小助,報下信息,藍小助會請您入群。歡迎您加入噢~~希望得到建議咨詢、商務(wù)合作,也請與我們聯(lián)系。

截屏2021-05-13 上午11.41.03.png


轉(zhuǎn)自:腳本之家

分享此文一切功德,皆悉回向給文章原作者及眾讀者.

免責(zé)聲明:藍藍設(shè)計尊重原作者,文章的版權(quán)歸原作者。如涉及版權(quán)問題,請及時與我們?nèi)〉寐?lián)系,我們立即更正或刪除。

藍藍設(shè)計www.bouu.cn )是一家專注而深入的界面設(shè)計公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計、BS界面設(shè)計 、 cs界面設(shè)計 、 ipad界面設(shè)計 、 包裝設(shè)計 、 圖標(biāo)定制 、 用戶體驗 、交互設(shè)計、 網(wǎng)站建設(shè) 、平面設(shè)計服務(wù)

分享本文至:

日歷

鏈接

個人資料

藍藍設(shè)計的小編 http://www.bouu.cn

存檔