事件節(jié)流和防抖是提高性能或降低網(wǎng)絡(luò)開(kāi)銷的好方法恍风。雖然 Vue 1曾經(jīng)支持對(duì)事件的節(jié)流和防抖蹦狂,但是在Vue 2中為了保持核心的簡(jiǎn)單性,刪除對(duì)事件的節(jié)流和防抖的支持朋贬。因此凯楔,在Vue 2對(duì)對(duì)事件進(jìn)行防抖和節(jié)流我們可以使用 lodash 這個(gè)js庫(kù)來(lái)做。
1. 安裝
使用 yarn 和 npm 安裝
// Yarn
yarn add lodash
// NPM
npm install lodash --save
2. throttle 方法
要對(duì)事件進(jìn)行節(jié)流處理方法非常簡(jiǎn)單锦募,只需將要調(diào)用的函數(shù)包裝在lodash的_.throttle函數(shù)中即可摆屯。
<template>
<button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
throttledMethod: _.throttle(function() {
console.log('I get fired every two seconds!')
}, 2000)
}
}
</script>
3. debounce 方法
盡管節(jié)流在某些情況下很有用,但一般情況我們經(jīng)常使用的是防抖糠亩。防抖實(shí)質(zhì)上將我們的事件分組在一起虐骑,并防止它們被頻繁觸發(fā)。要在Vue組件中使用節(jié)流赎线,只需將要調(diào)用的函數(shù)包裝在lodash的_.debounce函數(shù)中廷没。
當(dāng)前的項(xiàng)目是需要實(shí)時(shí)保存用戶在頁(yè)面中寫(xiě)入的信息,但是不可能每個(gè)字符都不停地保存到后端垂寥,所以使用 debounce 函數(shù)腕柜,將輸入一串字符停下后再進(jìn)行保存。
<template>
<button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
<script>
import _ from 'lodash'
export default {
methods: {
throttledMethod: _.debounce(function() {
console.log('I only get fired once every two seconds, max!')
}, 2000)
}
}
</script>
注意 throttling 和debouncing 回調(diào)函數(shù)使用function(){}矫废,這樣內(nèi)部才可以正常調(diào)用vue的this,否則會(huì)報(bào) undefined 砰蠢。因?yàn)樵诤瘮?shù)內(nèi)部中蓖扑,已經(jīng)做了apply,所以這里的this指向的就是vue實(shí)例台舱。