在 Vue 里使用 lodash 中的 Debouncing 和 Throttling
事件節(jié)流和防抖是提高性能或降低網(wǎng)絡(luò)開銷的好方法。雖然 Vue 1曾經(jīng)支持對(duì)事件的節(jié)流和防抖惯殊,但是在Vue 2中為了保持核心的簡(jiǎn)單性,刪除對(duì)事件的節(jié)流和防抖的支持祠锣。因此,在Vue 2對(duì)對(duì)事件進(jìn)行防抖和節(jié)流我們可以使用 lodash 來(lái)做牍疏。
安裝
可以通過(guò) yarn 或 npm 安裝 lodash黔酥。
# Yarn
$ yarn add lodash
# NPM
$ npm install lodash --save
注意:如果我們不想導(dǎo)入lodash的所有內(nèi)容,而只導(dǎo)入所需的部分苗踪,則可以通過(guò)一些Webpack構(gòu)建自定義來(lái)解決問(wèn)題。還可以使用lodash.throttle和lodash.debounce等軟件包分別安裝和導(dǎo)入lodash的各個(gè)部分削锰。
throttling 方法
要對(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>
debouncing 方法
盡管節(jié)流在某些情況下很有用器贩,但一般情況我們經(jīng)常使用的是防抖颅夺。防抖實(shí)質(zhì)上將我們的事件分組在一起,并防止它們被頻繁觸發(fā)蛹稍。要在Vue組件中使用節(jié)流吧黄,只需將要調(diào)用的函數(shù)包裝在lodash的_.debounce函數(shù)中。
<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