跳到主要内容

防抖

通过模块方式实现

:::details directive>debounce>index.js

import Vue from 'vue'
import debounce from "./debounce";
const install = function(Vue) {
Vue.directive("debounce", debounce);
};
if (window.Vue) {
window["debounce"] = debounce;
Vue.use(install);
}
debounce.install = install;
export default debounce;

:::

:::details directive>debounce>debounce.js

function debounce(fn, wait) {
let timer;
return function() {
/**
*@description:获取执行函数this指向
*/

let self = this;
/**
*@description:获取执行函数参数
*/
let args = arguments;
clearTimeout(timer);
timer = null;
timer = setTimeout(() => {
fn.apply(self, args);
}, wait);
};
}
export default {
bind(el, binding) {
/**
*@description: 指令传参数和指令不传参数的情况
*/
if (binding.value instanceof Array) {
const [func, time = 500] = binding.value;
el.execFun = debounce(func, time);
} else {
el.execFun = debounce(binding.value, 500);
}
el.addEventListener("click", el.execFun);
},
unbind(el) {
el.removeEventListener("click", el.execFun);
delete el.menuFun;
},
};

:::

:::details app.vue

<template>
<div id="app">
<button v-debounce="[() => handler('张文强'), 3000]">测试</button>
</div>
</template>

<script>
import debounce from "./directive/debounce";
export default {
name: "App",
directives: {
debounce,
},
methods: {
handler() {
console.log("张文强");
},
},
};
</script>

:::

通过组件方式实现

:::details utils>index.js

export function debounce(fn, wait) {
let timer;
return function() {
/**
* @description: 获取执行函数 this 指向
*/

let self = this;
/**
* @description: 获取执行函数 参数
*/
let args = arguments;
clearTimeout(timer);
/**
* @description: timer 用完置为 null ,防止内存泄漏
*/
timer = null;
timer = setTimeout(() => {
fn.apply(self, args);
}, wait);
};
}

:::

:::details app.vue

<template>
<div id="app">
<button v-debounce="[() => handler('张文强'), 3000]">测试</button>
</div>
</template>

<script>
import { debounce } from "./utils";
export default {
name: "App",
directives: {
debounce: {
bind(el, binding) {
/**
*@description:指令传参数和指令不传参数的情况
*/
if (binding.value instanceof Array) {
const [func, time = 500] = binding.value;
el.execFun = debounce(func, time);
} else {
el.execFun = debounce(binding.value, 500);
}
el.addEventListener("click", el.execFun);
},
unbind(el) {
el.removeEventListener("click", el.execFun);
},
},
},
methods: {
handler() {
console.log("张文强");
},
},
};
</script>

:::