防抖的概念 防抖又叫为函数防抖(debounce):指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间。 前端开发中,常见的事件如,onresize,scroll,mousemove ,mousehover 等会短时间内多次触发(频繁触发…
防抖的概念
防抖又叫为函数防抖(debounce):指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间。
前端开发中,常见的事件如,onresize,scroll,mousemove ,mousehover 等会短时间内多次触发(频繁触发),不做限制的话可能一秒执行几百次,在这些函数内部如果还执行了其他函数,尤其是执行了操作 DOM 的函数的话(浏览器操作 DOM 是很耗费性能的),那不仅会浪费计算机资源,还会降低程序运行速度,甚至造成浏览器卡死、崩溃。
除此之外,短时间内重复调用 ajax 不仅会造成数据关系的混乱,还会造成网络拥堵,增加服务器压力等问题。
按钮防抖
import { debounce } from 'lodash';
<divv-for="(item, index) in summaryData":key="index"@click="handleFun(item, index)">
</div>
methods: {// 点击handleFun: debounce(function (item, index) {console.log(item,this)}, 300),
}
自定义指令防抖
directive.js
import Vue from "vue";
import { debounce } from "lodash";export default Vue.directive("debounceClick", {inserted: function (el, binding) {let delayTime = el.getAttribute("delay-time") || 500;el.onclick = debounce(function () {binding.value();}, delayTime);},
});
main.js引入
import "@/utils/directive";
页面使用
<template><div id="app"><button v-debounceClick="debounce">防抖</button></div>
</template><script>export default {name: "App",components: {},methods: {debounce() {console.log(111);},},
};
</script><style></style>