需求:控制用户对按钮得不断地点击,因为点击按钮会不断地发请求,加重网络负担,对此进行优化
节流防抖的代码转载 https://blog.csdn.net/weixin_/article/details/
1、节流防抖写成一个公用的js文件(这是一种思维,尽量把一些公用的提取为js文件,所有vue组件都可以进行引入,让我们的代码更规范、更好看、可维护性更高,为此我还在不断地努力)
/ * 函数防抖 (只执行最后一次点击) * @param fn * @param delay * @returns {Function} * @constructor */ export const Debounce = (fn, t) => { let delay = t || 500; let timer; console.log(fn) console.log(typeof fn) return function () { let args = arguments; if(timer){ clearTimeout(timer); } timer = setTimeout(() => { timer = null; fn.apply(this, args); }, delay); } }; / * 函数节流 * @param fn * @param interval * @returns {Function} * @constructor */ export const Throttle = (fn, t) => { let last; let timer; let interval = t || 500; return function () { let args = arguments; let now = +new Date(); if (last && now - last < interval) { clearTimeout(timer); timer = setTimeout(() => { last = now; fn.apply(this, args); }, interval); } else { last = now; fn.apply(this, args); } } }
2、vue组件里引入节流防抖文件(路径需要根据自己的情况)
import {Debounce} from "../../../service/utils/public";
用户如果对按钮进行多次点击,只针对最后一次的点击发送请求
methods:{ changeStatus:Debounce(function(row){ APIService.changeMsg({msg_id:row.msg_id,status:0}).then((data)=>{ this.teacherGetMsg();//点击按钮后的逻辑代码存放的方法 }).catch((error)=>{ console.log('error请求失败',error) }) },500), }
学习的过程中,肯定会遇到大大小小的问题,很庆幸,这些问题都成为我们成长的垫脚石,不要怕遇到问题,办法总比困难多,总有一刻,就顿悟了
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214367.html原文链接:https://javaforall.net
