vue3+ts如何通過lodash實現(xiàn)防抖節(jié)流詳解
安裝lodash
npm i --save-dev @types/lodash
在組件中引入lodash
import * as _ from 'lodash'
防抖
_.debounce(func, [wait=0], [options=]) 函數(shù)在延遲幾毫秒之后才執(zhí)行,也就是停止改變幾秒后執(zhí)行
參數(shù)
- func (Function): 要防抖動的函數(shù)。
- [wait=0] (number): 需要延遲的毫秒數(shù)。
- [options=] (Object): 選項對象。
- [options.leading=false] (boolean): 指定在延遲開始前調(diào)用。
- [options.maxWait] (number): 設(shè)置 func 允許被延遲的最大值。
- [options.trailing=true] (boolean): 指定在延遲結(jié)束后調(diào)用。
<script setup lang="ts"> import * as _ from 'lodash' //防抖的函數(shù)應(yīng)該是click事件 const fangdou = _.debounce(click, 500, { leading: true, // 延長開始后調(diào)用 trailing: false // 延長結(jié)束前調(diào)用 }) function click() { //響應(yīng)點擊 console.log("123") } //移除組件時,取消防抖 onUnmounted(()=>{ fangdou.cancel() }) </script> <template> <button @click="fangdou">fangdou</button> </template>
節(jié)流
_.throttle(func, [wait=0], [options=]) 第一次會立即執(zhí)行一次,然后等到過了毫秒數(shù)才會執(zhí)行,以一定的頻率后續(xù)處理
參數(shù)
- func (Function): 要節(jié)流的函數(shù)。
- [wait=0] (number): 需要節(jié)流的毫秒。
- [options=] (Object): 選項對象。
- [options.leading=true] (boolean): 指定調(diào)用在節(jié)流開始前。
- [options.trailing=true] (boolean): 指定調(diào)用在節(jié)流結(jié)束后。
<script setup lang="ts"> import * as _ from 'lodash' const throttle = _.throttle(() =>{ console.log('I get fired every two seconds!') },2000,{ leading: true, trailing: false }) //移除組件時,取消節(jié)流 onUnmounted(()=>{ throttle.cancel() }) </script> <template> <button @click="throttle">jieliu</button> </template>
補充:vue3 引入lodash報錯
在 shims-vue.d.ts 文件夾下添加
declare module 'lodash'
全部代碼
/* eslint-disable */ declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } declare module 'lodash'
總結(jié)
到此這篇關(guān)于vue3+ts如何通過lodash實現(xiàn)防抖節(jié)流的文章就介紹到這了,更多相關(guān)vue3+ts lodash防抖節(jié)流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
element-plus/element-ui走馬燈配置圖片及圖片自適應(yīng)的最簡便方法
走馬燈功能在展示圖片時經(jīng)常用到,下面這篇文章主要給大家介紹了關(guān)于element-plus/element-ui走馬燈配置圖片及圖片自適應(yīng)的最簡便方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03reactive readonly嵌套對象轉(zhuǎn)換功能實現(xiàn)詳解
這篇文章主要為大家介紹了reactive readonly嵌套對象轉(zhuǎn)換功能實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12在vue中實現(xiàn)給每個頁面頂部設(shè)置title
這篇文章主要介紹了在vue中實現(xiàn)給每個頁面頂部設(shè)置title,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07解決ant-design-vue中menu菜單無法默認(rèn)展開的問題
這篇文章主要介紹了解決ant-design-vue中menu菜單無法默認(rèn)展開的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10vue使用axios實現(xiàn)文件上傳進(jìn)度的實時更新詳解
最近在學(xué)習(xí)axios,然后項目就用到了,所以這篇文章主要給大家介紹了關(guān)于vue中利用axios實現(xiàn)文件上傳進(jìn)度的實時更新的相關(guān)資料,文中先對axios進(jìn)行了簡單的介紹,方法大家理解學(xué)習(xí),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12詳解Vue2.x-directive的學(xué)習(xí)筆記
這篇文章主要介紹了詳解Vue2.x-directive的學(xué)習(xí)筆記,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07