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

vue3+ts如何通過lodash實現(xiàn)防抖節(jié)流詳解

 更新時間:2022年08月10日 10:06:26   作者:qq_45489665  
loadsh是一個工具庫,我們通常使用loadsh的debounce函數(shù)處理防抖,下面這篇文章主要給大家介紹了關(guān)于vue3+ts如何通過lodash實現(xiàn)防抖節(jié)流的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下

安裝lodash

npm i --save-dev @types/lodash

在組件中引入lodash

import * as _ from 'lodash'

防抖

_.debounce(func, [wait=0], [options=]) 函數(shù)在延遲幾毫秒之后才執(zhí)行,也就是停止改變幾秒后執(zhí)行

參數(shù)

  1. func (Function): 要防抖動的函數(shù)。
  2. [wait=0] (number): 需要延遲的毫秒數(shù)。
  3. [options=] (Object): 選項對象。
  4. [options.leading=false] (boolean): 指定在延遲開始前調(diào)用。
  5. [options.maxWait] (number): 設(shè)置 func 允許被延遲的最大值。
  6. [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ù)

  1. func (Function): 要節(jié)流的函數(shù)。
  2. [wait=0] (number): 需要節(jié)流的毫秒。
  3. [options=] (Object): 選項對象。
  4. [options.leading=true] (boolean): 指定調(diào)用在節(jié)流開始前。
  5. [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)文章

最新評論