赞
踩
在src/utils文件夹中新建文件handleDebounce.js,用于封装防抖和节流
- // 防抖
- export function debounce(fn, delay = 200) {// fn是需要防抖的函数,delay是延迟多少毫秒执行fn
- let timer = null;
- return function () {
- if (timer) {
- clearTimeout(timer);
- }
- timer = setTimeout(() => {
- fn.apply(fn, arguments);
- timer = null;
- }, delay)
- }
- }
-
- // 节流
- export function throttle(fn, delay = 100) {
- let timer = null;
- return function () {
- if (timer) return;
- timer = setTimeout(() => {
- fn.apply(fn, arguments);
- timer = null;
- }, delay)
- }
- }
- <el-button @click="clickEvent">防抖</el-button>
- <el-button @click="clickEvent2">节流</el-button>
-
-
- import { debounce,throttle } from "@/utils/handleDebounce";
-
- const clickEvent = debounce(
- () => {
- console.log("防抖");
- }, 800);
-
- const clickEvent2 = throttle(
- () => {
- console.log("节流");
- }, 800);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。