欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js節(jié)流防抖應(yīng)用場(chǎng)景,以及在vue中節(jié)流防抖的具體實(shí)現(xiàn)操作

 更新時(shí)間:2020年09月21日 10:56:26   作者:進(jìn)軍的蝸牛  
這篇文章主要介紹了js節(jié)流防抖應(yīng)用場(chǎng)景,以及在vue中節(jié)流防抖的具體實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

故事背景:

項(xiàng)目有個(gè)需求是輸入框在輸入的時(shí)候進(jìn)行搜索,展示下拉數(shù)據(jù),但是沒必要輸入一個(gè)字都進(jìn)行搜索,所以想到了在輸入結(jié)束200毫秒后再進(jìn)行搜索,從而引出來了 js的節(jié)流(throttle),防抖(debounce),在網(wǎng)上想找個(gè)現(xiàn)成的用下,但是好多都不對(duì),于是就自己搞了。

先看看概念

函數(shù)防抖(debounce):

在事件被觸發(fā)n秒后再執(zhí)行回調(diào),如果在這n秒內(nèi)又被觸發(fā),則重新計(jì)時(shí);典型的案例就是輸入搜索:輸入結(jié)束后n秒才進(jìn)行搜索請(qǐng)求,n秒內(nèi)又輸入的內(nèi)容,就重新計(jì)時(shí)。

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

規(guī)定在一個(gè)單位時(shí)間內(nèi),只能觸發(fā)一次函數(shù),如果這個(gè)單位時(shí)間內(nèi)觸發(fā)多次函數(shù),只有一次生效; 典型的案例就是鼠標(biāo)不斷點(diǎn)擊觸發(fā),規(guī)定在n秒內(nèi)多次點(diǎn)擊只有一次生效。

setTimeout內(nèi) this失效:

這是由于setTimeout函數(shù)調(diào)用的代碼運(yùn)行在與所在函數(shù)完全分離的執(zhí)行環(huán)境上,這會(huì)使得this指向的是window對(duì)象,看下圖 :

打了斷點(diǎn),在Console下輸出 this 是Window對(duì)象,解決這個(gè)問題可以在setTimeout函數(shù)外面定義一個(gè) that = this 就可以了,輸出 that果然就是該組件的對(duì)象

看在vue中的實(shí)際代碼:

1.輸入框,輸入最后一個(gè)字 2秒后執(zhí)行(防抖:debounce):

html:

<input type="text" class="input" v-model="searchText" @keyup="debounce"/>

js:

    debounce: function(){
      let that = this
      if(timer){
        clearTimeout(timer)
      }
      timer = setTimeout(function () {
        console.log('輸入')
        timer = undefined;
      },2000)
    }

timer 不要放在 debounce函數(shù)內(nèi)部,要在文件全局定義,如下所示:

效果演示如下(輸入一次文字2秒后執(zhí)行,多次輸入,還是執(zhí)行一次,成功):

2.在2秒內(nèi)多次點(diǎn)擊,只有一次生效(節(jié)流:throttle):

html:

<div @click="throttle">點(diǎn)我。。</div>

js:

    throttle: function(){
      let that = this
      let now = +new Date();
      if(lastTime && lastTime - now < 2000){
        clearTimeout(timer)
      }
      timer = setTimeout(function () {
        console.log('點(diǎn)擊')
        lastTime = +new Date()
      },200)
    }

lastTime 跟 timer一樣,都要定義在文件的全局,如下:

效果圖如下:第一次點(diǎn)擊一下輸出一次,第二次雙擊選中,又輸出一次,成功。

補(bǔ)充知識(shí):VUE防抖與節(jié)流的最佳解決方案——函數(shù)式組件

前言

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

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

函數(shù)防抖(debounce)

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

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

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

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

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

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

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ù)都會(huì)更新prev用來記錄本次執(zhí)行的時(shí)間,下一次事件觸發(fā)時(shí)判斷時(shí)間間隔是否到達(dá)預(yù)先的設(shè)定,重復(fù)上述操作。

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

在vue中的實(shí)踐

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

封裝utils工具

封裝組件

封裝utils工具

把上面的案例改造一下就能封裝一個(gè)簡(jiǎn)單的utils工具

utils.js

let timeout = null
function debounce(fn, wait) {
 if(timeout !== null) clearTimeout(timeout)
 timeout = setTimeout(fn, wait)
}
export default debounce

app.js

<input type="text" @input="debounceInput($event)">
 
import debounce from './utils'
export default {
 methods: {
  debounceInput(E){
   debounce(() => {
    console.log(E.target.value)
   }, 1000)
  }
 }
}

封裝組件

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

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

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

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

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

debounce-input.vue

<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

<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)注屬性的傳遞,但是在使用上還是不方便的,因?yàn)榘裡l-input封裝在了內(nèi)部這樣對(duì)樣式的限定也比較局限。有接觸過react高階組件的同學(xué)可能有了解,react高階組件本質(zhì)上是一個(gè)函數(shù)通過包裹被傳入的React組件,經(jīng)過一系列處理,最終返回一個(gè)相對(duì)增強(qiáng)的React組件。那么在vue中可以借鑒這種思路嗎,我們來了解一下vue的函數(shù)式組件。

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

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

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

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

export default () => {
 functional: true, 
 props: { 
  // Props 是可選的
 },
 // 為了彌補(bǔ)缺少的實(shí)例, 提供第二個(gè)參數(shù)作為上下文
 render: function (createElement, context) {
  return vNode
 }
}

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

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

props:提供所有 prop 的對(duì)象

children: VNode 子節(jié)點(diǎn)的數(shù)組

slots: 一個(gè)函數(shù),返回了包含所有插槽的對(duì)象

scopedSlots: (2.6.0+) 一個(gè)暴露傳入的作用域插槽的對(duì)象。也以函數(shù)形式暴露普通插槽。

data:傳遞給組件的整個(gè)數(shù)據(jù)對(duì)象,作為 createElement 的第二個(gè)參數(shù)傳入組件

parent:對(duì)父組件的引用

listeners: (2.3.0+) 一個(gè)包含了所有父組件為當(dāng)前組件注冊(cè)的事件監(jiān)聽器的對(duì)象。這是 data.on 的一個(gè)別名。

injections: (2.3.0+) 如果使用了 inject 選項(xiàng),則該對(duì)象包含了應(yīng)當(dāng)被注入的屬性。

vm.$slots API 里面是什么

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

slots() 和 children 對(duì)比

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

<my-functional-component>
 <p v-slot:foo>
  first
 </p>
 <p>second</p>
</my-functional-component>

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

一個(gè)函數(shù)式組件的使用場(chǎng)景

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

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

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

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í)該組件同樣擁有上下文以及生命周期函數(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)下面組件的任意一個(gè)且唯一 el-button、el-input、button、input')
   return vnode
  }
  return vnode
 }
}
<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>

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

自定義指令 directive

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

以上這篇js節(jié)流防抖應(yīng)用場(chǎng)景,以及在vue中節(jié)流防抖的具體實(shí)現(xiàn)操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論