vue3.0封装防抖和节流

vue3.0封装防抖和节流

1.节流和防抖

节流
点击事件,在一段事件内连续点击,指定时间内只触发一次

防抖
点击后1秒之后再触发事件相当于setTimeout

在utils文件下创建throttle.js
// 节流
export  const throttle=(fn, time)=> {
    let timer = null
    time = time || 1000
    return function(...args) {
        if (timer) {
            return
        }
        const _this = this
        timer = setTimeout(() => {
            timer = null
        }, time)
        fn.apply(_this, args)
    }
}

// 防抖
export const debounce=(fn, time)=> {
    time = time || 200
    // 定时器
    let timer = null
    return function(...args) {
        const _this = this;
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function() {
            timer = null
            fn.apply(_this, args)
        }, time)
    }
}

在页面中使用
<template>
  <div>
    <el-button type="primary" plain @click="btnClick">节流</el-button>
    <el-button type="primary" plain @click="btnClick2">防抖</el-button>
  </div>
</template>

<script setup>
import {throttle,debounce} from '@/utils/throttle'
// 节流
const btnClick=throttle((e) => {
  console.log('节流')
}, 1500)
// 防抖
const btnClick2=debounce((e) => {
  console.log('防抖')
}, 1000)
</script>

<style scoped>
</style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中,可以通过封装节流函数来优化页面性能和用户体验。节流都是为了限制函数的执行频率,避免频繁触发函数而导致性能问题。 1. (Debounce):在指定的时间间隔内,如果事件持续触发,则重新计时,直到事件停止触发后才执行函数。常用于输入框搜索、窗口调整等场景。 下面是一个通过Vue封装函数的示例: ```javascript // 函数 function debounce(func, delay) { let timer = null; return function() { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, arguments); }, delay); }; } // Vue组件中使用函数 export default { data() { return { inputValue: '' }; }, methods: { handleInput: debounce(function() { // 处理输入事件 // ... }, 300) } } ``` 2. 节流(Throttle):在指定的时间间隔内,只执行一次函数。常用于滚动加载、按钮点击等场景。 下面是一个通过Vue封装节流函数的示例: ```javascript // 节流函数 function throttle(func, delay) { let timer = null; return function() { if (!timer) { timer = setTimeout(() => { func.apply(this, arguments); timer = null; }, delay); } }; } // Vue组件中使用节流函数 export default { data() { return { scrollPosition: 0 }; }, mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeDestroy() { window.removeEventListener('scroll', this.handleScroll); }, methods: { handleScroll: throttle(function() { // 处理滚动事件 // ... }, 300) } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值