# 工具类

# 1 目录结构

└─ utils                    # 公共方法
  └─ index.js               # 一些工具函数

# 主要函数

以下主要介绍防抖与节流函数的作用以及使用方式

# 防抖函数

释义:一段时间内多次触发时,只执行最后一次。
使用:如模糊搜索时,当用户短时间内连续输入文字,则只触发最后一次。 本项目使用模块:搜索页

// 函数
export const debounce = (func, wait = 100) => {
  let timeout;
  return function (event) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.call(this, event);
    }, wait);
  };
}

// 使用
import { debounce } from "@/util";

// input 触发的搜索事件
methods: {
  doSearch: debounce(function () {
      // 结果 debounce 处理后执行的搜索方法
      this.search();
  }),
  async search() {

  }
}

# 节流函数

释义:防止事件触发频率太高,只每隔一段时间触发一次。
使用:如 scroll 事件,页面滚动时会一直高频率触发,需要每隔一段时间执行一次,以减小计算压力。 本项目使用模块:header-bar

// 函数
export const throttle = (cb, wait = 1000 / 60) => {
  let last = 0;
  return function () {
    var now = new Date().getTime();;
    if (now - last > wait) {
      cb.call(this, ...arguments);
      last = new Date().getTime();;
    }
  }
}

# 使用

// app.js
import { debounce, throttle } from "./utils/index"

App({
  
  // ...
  debounce,

  throttle,
})
const app = getApp()

Page({
  onPageScroll: app.throttle(function ({scrollTop}) {
    this.setData({
      scrollTop
    })
  })
})
上次更新: 2022-10-25 9:05:36 ├F10: PM┤