使用 lodash封装 防抖韩式vue3和vue2使用方法;自定义防抖节流

npm i --save lodash 

vue3




<template>
<el-button @click="debouncedClick">获取数据</el-button>
</template>

<script>
import { ref } from 'vue';
import _ from 'lodash';

export default {
setup() {
const fetchData = () => {
// 这里是你的获取数据的逻辑
console.log('Fetching data...');
// 例如,使用 axios 发送请求
};

// 创建一个防抖函数,等待 300 毫秒
const debouncedClick = _.debounce(fetchData, 300);

// 注意:因为 debounce 函数会返回一个新的函数,
// 所以我们需要确保在模板中引用的是这个新的函数。

return {
debouncedClick,
};
},
};
</script>
Vue2 
    <el-button @click="clickButton">获取数据</el-button>
      clickButton: _.debounce(
      
Vue使用lodash来实现节流防抖方法如下: 1. 安装lodash库:在项目根目录下打开命令行工具,执行以下命令安装lodash库: ``` npm install lodash ``` 2. 导入lodash库:在需要使用节流防抖的组件中,导入lodash库的相关函数: ```javascript import { debounce, throttle } from 'lodash'; ``` 3. 使用节流函数:使用`throttle`函数来实现节流。`throttle`函数会在指定的时间间隔内只执行一次函数,可以用于限制频繁触发的事件,例如滚动、拖拽等。以下是一个使用节流函数的示例: ```javascript export default { data() { return { scrollHandler: null }; }, methods: { handleScroll() { // 处理滚动事件的逻辑 console.log('Scroll event'); } }, mounted() { this.scrollHandler = throttle(this.handleScroll, 200); // 设置节流时间为200ms window.addEventListener('scroll', this.scrollHandler); }, beforeDestroy() { window.removeEventListener('scroll', this.scrollHandler); } } ``` 在上述代码中,使用`throttle`函数将`handleScroll`方法包装起来,设置节流时间为200ms。在组件的`mounted`生命周期钩子中,将节流后的处理函数添加到`scroll`事件监听器中,保证在指定时间间隔内只执行一次。 4. 使用防抖函数:使用`debounce`函数来实现防抖。`debounce`函数会在指定的时间间隔后执行函数,如果在这个时间间隔内又触发了同样的函数,则重新计时。以下是一个使用防抖函数的示例: ```javascript export default { data() { return { inputHandler: null, inputValue: '' }; }, methods: { handleInput() { // 处理输入事件的逻辑 console.log('Input event'); } }, mounted() { this.inputHandler = debounce(this.handleInput, 500); // 设置防抖时间为500ms } } ``` 在上述代码中,使用`debounce`函数将`handleInput`方法包装起来,设置防抖时间为500ms。在组件的`mounted`生命周期钩子中,将防抖后的处理函数赋值给`inputHandler`。 在模板中,将防抖处理函数绑定到相应的事件上: ```html <input type="text" v-model="inputValue" @input="inputHandler"> ``` 这样,在输入框输入内容时,只有在500ms内没有再次输入才会触发防抖后的处理函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小云儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值