vue3+ts如何通过lodash实现防抖节流详解

Kathy ·
更新时间:2024-09-20
· 141 次阅读

目录

安装lodash

防抖

节流

补充:vue3 引入lodash报错

总结

安装lodash npm i --save-dev @types/lodash

在组件中引入lodash

import * as _ from 'lodash' 防抖

_.debounce(func, [wait=0], [options=]) 函数在延迟几毫秒之后才执行,也就是停止改变几秒后执行

参数

func (Function): 要防抖动的函数。

[wait=0] (number): 需要延迟的毫秒数。

[options=] (Object): 选项对象。

[options.leading=false] (boolean): 指定在延迟开始前调用。

[options.maxWait] (number): 设置 func 允许被延迟的最大值。

[options.trailing=true] (boolean): 指定在延迟结束后调用。

<script setup lang="ts"> import * as _ from 'lodash' //防抖的函数应该是click事件 const fangdou = _.debounce(click, 500, { leading: true, // 延长开始后调用 trailing: false // 延长结束前调用 }) function click() { //响应点击 console.log("123") } //移除组件时,取消防抖 onUnmounted(()=>{ fangdou.cancel() }) </script> <template> <button @click="fangdou">fangdou</button> </template> 节流

_.throttle(func, [wait=0], [options=]) 第一次会立即执行一次,然后等到过了毫秒数才会执行,以一定的频率后续处理

参数

func (Function): 要节流的函数。

[wait=0] (number): 需要节流的毫秒。

[options=] (Object): 选项对象。

[options.leading=true] (boolean): 指定调用在节流开始前。

[options.trailing=true] (boolean): 指定调用在节流结束后。

<script setup lang="ts"> import * as _ from 'lodash' const throttle = _.throttle(() =>{ console.log('I get fired every two seconds!') },2000,{ leading: true, trailing: false }) //移除组件时,取消节流 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' 总结

到此这篇关于vue3+ts如何通过lodash实现防抖节流的文章就介绍到这了,更多相关vue3+ts lodash防抖节流内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE lodash ts

需要 登录 后方可回复, 如果你还没有账号请 注册新账号