vue 防抖与节流用法

一、html

<template>
    <button @click="getData">获取数据</button>
</template>

二、JS

import { throttle } from "@/utils/common";
export default {
    methods:{
        getData: throttle(async function(params){
            console.log(”获取接口数据“,this,parmas)
        })
    }
}

三、公共方法 common.js

// 节流
export const throttle = function (cb, delay) {
  let timer = null;
  return function (...arg) {
    if (timer) return;
    cb.call(this, arg[0]);
    timer = setTimeout(() => {
      timer = null;
    }, delay);
  };
};
// 防抖
export const debounce = function (cb, delay) {
  let timer = null;
  return function (...arg) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      cb.call(this, arg[0]);
    }, delay);
  };
};

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