淺析VUE防抖與節(jié)流
防抖和節(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è)簡單的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)部組件。
簡單來說$listeners、$attrs他倆是做屬性和事件的承接,這在對(duì)組件做二次封裝的時(shí)候非常有用。
我們以element-ui的el-input組件為例封裝一個(gè)帶防抖的debounce-input組件
debounce-input.vue
<template>
<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)榘裪nput封裝在了內(nèi)部這樣對(duì)樣式的限定也比較局限。有接觸過react高階組件的同學(xué)可能有了解,react高階組件本質(zhì)上是一個(gè)函數(shù)通過包裹被傳入的React組件,經(jīng)過一系列處理,最終返回一個(gè)相對(duì)增強(qiáng)的React組件。那么在vue中可以借鑒這種思路嗎,我們來了解一下vue的函數(shù)式組件。
函數(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 類似的嗎?在一些場景中,是這樣——但如果是如下的帶有子節(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ī)制,還是簡單地通過傳遞 children,移交給其它組件去處理。
一個(gè)函數(shù)式組件的使用場景
假設(shè)有一個(gè)a組件,引入了 a1,a2,a3 三個(gè)組件,a組件的父組件給a組件傳入了一個(gè)type屬性根據(jù)type的值a組件來決定顯示 a1,a2,a3 中的那個(gè)組件。這樣的場景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
}
}
原理也很簡單就是在vNode中攔截on下面的click、input事件做防抖處理,這樣在使用上就非常簡單了。
自定義指令 directive
我們來思考一個(gè)問題,函數(shù)式組件封裝防抖的關(guān)節(jié)是獲取vNode,那么我們通過自定義指令同樣可以拿到vNode,甚至還可以得到原生的Dom,這樣用自定義指令來處理會(huì)更加方便。。。。。。
自定義指令:https://cn.vuejs.org/v2/guide/custom-directive.html
main.js
Vue.directive("dinput", {
bind: function(el, binding, vnode) {
let timeout = null;
el.addEventListener("input", function() {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(function() {
vnode.context[binding.expression]();
}, 1000);
});
}
});
vue
<input type="text" v-dinput="myfunc"/>
js
export default {
name: "App",
data: function() {
return {
loginuser: null
};
},
methods: {
myfunc() {
console.info("myfunc");
}
}
}
這種方式的缺點(diǎn)
調(diào)用方法時(shí)無法傳參
以上就是淺析VUE防抖與節(jié)流的詳細(xì)內(nèi)容,更多關(guān)于VUE 防抖與節(jié)流的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue生命周期activated之返回上一頁不重新請(qǐng)求數(shù)據(jù)操作
這篇文章主要介紹了Vue生命周期activated之返回上一頁不重新請(qǐng)求數(shù)據(jù)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue使用json-server進(jìn)行后端數(shù)據(jù)模擬功能
這篇文章主要介紹了Vue使用json-server進(jìn)行后端數(shù)據(jù)模擬功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-04-04
Vue.js實(shí)現(xiàn)一個(gè)todo-list的上移下移刪除功能
這篇文章主要介紹了Vue.js實(shí)現(xiàn)一個(gè)todo-list的上移下移刪除功能,需要的朋友可以參考下2017-06-06
Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼
本文主要介紹了Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼,通過監(jiān)聽文件選擇事件和使用FileReader API,可以實(shí)現(xiàn)視頻文件的預(yù)覽功能,感興趣的可以了解一下2025-01-01
vue監(jiān)聽滾動(dòng)條頁面滾動(dòng)動(dòng)畫示例代碼
Vue是一套用于構(gòu)建用戶界面的漸進(jìn)式框架,與其它大型框架不同的是,Vue?被設(shè)計(jì)為可以自底向上逐層應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于vue監(jiān)聽滾動(dòng)條頁面滾動(dòng)動(dòng)畫的相關(guān)資料,需要的朋友可以參考下2023-06-06

