# 工具类

# 1 目录结构

└─ src                          # 项目主文件
   └─ util                      # 全局过滤器
      ├─ color.js               # 颜色64进制转rgba
      └─ index.js               # 一些工具函数

# 主要函数

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

# 防抖函数

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

// 函数
const debounce = (func, wait = 200) => {
  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

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

// 使用
mounted() {
  window.addEventListener("scroll", this.getScrollTop);
},
methods: {
  handleScroll: throttle(function () {
    this.getScrollTop();
  }),

  getScrollTop() {
    this.scrollTop = document.documentElement.scrollTop;
  },
},
上次更新: 6/27/2022, 5:48:02 PM
示例展示,因PC端无touch事件,请在手机上进行浏览