vue中的防抖和节流

防抖(debounce)是指在事件被触发 n 秒后才执行回调函数,如果在这段时间内再次触发了事件,则重新计时。防抖的主要作用是防止重复提交或重复操作。

引入  npm i --save lodash  网址 Lodash 简介 | Lodash 中文文档 | Lodash 中文网




使用自定义指令 实现防抖




vue中使用手写防抖




 vue中的throttle




函数节流

function throttle(func, delay) {
  let prevTime = 0;
  return function() {
    const context = this;
    const args = arguments;
    const currTime = Date.now();
    if (currTime - prevTime > delay) {
      func.apply(context, args);
      prevTime = currTime;
    }
  };
}

 它接受两个参数:一个是要执行的函数 func,另一个是节流的时间间隔 delay。当调用返回的函数时,它会检查当前时间与上一次调用的时间间隔是否超过了节流的时间间隔,如果超过了,则执行传入的函数 func,否则不执行。

 vue中使用节流的自定义指令  针对于点击按钮的效果





//还可以  定义时间


vue中使用库点击按钮节流

import { throttle } from 'lodash';

export default {
  methods: {
    handleClick: throttle(function() {
      console.log('Button clicked!');
    }, 1000)
  }
}

在上面的代码中,throttle 函数接受两个参数:真正的点击事件处理函数和一个时间间隔,单位为毫秒。throttle 函数将返回一个新的函数,这个函数将在指定的时间间隔内最多执行一次真正的点击事件处理函数。

你可能感兴趣的:(vue.js,javascript,前端)