vue3 在SetUp函数中封装防抖和节流

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>

猜你喜欢

转载自blog.csdn.net/H_jrqn/article/details/129276678