在vue3中对watch监听的函数添加防抖

401 阅读1分钟
const getData = debounce(getMeetingRoomList, 2000);
function debounce(fun: Function, delay: number) {
  let timeoutID: number;
  return function () {
    if (timeoutID) {
      clearTimeout(timeoutID);
    }
    timeoutID = setTimeout(() => {
      fun.apply(this, arguments);
    }, delay);
  };
}
watch(searchMeetingRoomData, () => {
  getData();
},{immediate: true});

这里this会报个错this" 隐式具有类型 "any",因为它没有类型注释。

解决:

const getData = debounce(getMeetingRoomList, 300);
//把this写在参数的地方即可
function debounce(this:any,fun: Function, delay: number) {
  let timeoutID: number;
  let that = this
  return function () {
    if (timeoutID) {
      clearTimeout(timeoutID);
    }
    timeoutID = setTimeout(() => {
      fun.apply(that, arguments);
    }, delay);
  };
}
watch(searchMeetingRoomData, () => {
  getData();
},{immediate: true});