【防抖函数】vue封装防抖函数

第一步:创建一个js文件,复制进去

/**
 * @desc 防抖函数
 * @param {需要防抖的函数} func
 * @param {延迟时间} wait
 * @param {是否立即执行} immediate
 */

//防抖函数用法:

//结构正常写
/* <el-button type="primary" @click="jump('参数')">查询</el-button> */

//methods方法这么写:这里注意function可以让你this指向实例
//  jump: debounce(
//     function (参数) {
    
    
//       console.log(参数);
//     },
//     500, //间隔时间
//     true //是否立即执行
//   ),

 export function debounce(func, wait, immediate) {
    
    
    let timeout //计时器
    return function (...args) {
    
    //args就是传的参数
      let context = this 
      if (timeout) clearTimeout(timeout)//如果有计时器就清除计时器
      if (immediate) {
    
     //如果立即执行设置为true
        let callNow = !timeout //定时器为空就是true
        timeout = setTimeout(function() {
    
    //开启定时器
          timeout = null
        }, wait)//wait:定时器的时间
        if (callNow) func.apply(context, args)//定时器为空的话就执行把传进来的函数指向改变为这个防抖函数,然后把参数传给这个防抖函数。通过return把参数返回。
      } else {
    
    
        //立即执行为false就开个定时器在执行这个函数
        timeout = setTimeout(function() {
    
    
          func.apply(context, args)
        }, wait)
      }
    }
  }
  

第二步:引入这个js

路径自己看着要不要改一下,我放在utils内的

import {
    
     debounce } from "@/utils/debounce.js";

第三步:使用

结构:

<el-button type="primary" @click="ceshi('测试防抖')">查询</el-button>

methods:这里注意function加了是因为可以让你this指向为当前实例,如果用箭头函数就指向不生效了。无法组件其他外部变量

  methods: {
    
    
    //防抖函数测试
    ceshi: debounce(
      function (vm) {
    
    
        console.log(vm, this.a, "ceshi111");
      },
      500,
      true
    ),
    }

猜你喜欢

转载自blog.csdn.net/seeeeeeeeeee/article/details/121536813
今日推荐