[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>防抖和节流
前端在调动接口时,常常要控制接口的请求频率,这时我们就可以使用防抖和节流两种方式来控制。
<>什么是防抖和节流,两者的区别是什么
* 防抖:
防抖就是在行为触发执行一次后,需静默等待N秒后才能再次执行,在此期间不能再触发行为,如果重复触发就计时归零后再次计时,直到用户静默到设定的阈值才再次执行。简而言之就是触发后N秒内不许触发,直到N秒后才可以执行。
* 节流: 节流就是N秒内只执行一次,不管在N秒内重复调用了多少次,也只执行一次。
<>注:以下是在VUE中以自定义指令形式实现的防抖和节流,是笔者按照自己的想法来实现的,可优化。
<>1、首先创建防抖节流JS文件
import Vue from "vue" // 防抖 Vue.directive('shake', { inserted(el, binding) {
let { fn, event = "click", delay = 800 } = binding.value; let timerA = null; el.
addEventListener( event, () => { if (timerA) { clearTimeout(timerA) timerA =
null timerA = setTimeout(() => { fn.apply(this, arguments); clearTimeout(timerA)
timerA= null }, delay); } else { fn.apply(this, arguments); timerA = setTimeout
(() => { clearTimeout(timerA) timerA = null }, delay); } }, false ); }, }); //
节流 Vue.directive('throttling', { inserted(el, binding) { let { fn, event =
"click", delay = 800 } = binding.value; let timerB = null; let flag = true el.
addEventListener(event, () => { if (flag) { flag = false fn.apply(this,
arguments); timerB = setTimeout(() => { flag = true clearTimeout(timerB); timerB
= null }, delay); } }); }, });
<>2、然后在main.js中引入
import "@/util/shakeAndThrottling.js"
<>3、使用示例
<el-button primary v-throttling="{fn:changeTestObj,event:'click',delay:2000}">加
+ 加</el-button>
注:如果有看不懂的再认真看一遍就懂了。