项目场景:
提示:防抖传参
回车事件,加上防抖,传递对应的上下文参数,上网搜索无果,对现有的指令方法加以改进
<!-- index.vue -->
<template>
<div>
<button v-debounce.enter="handleKeyPress">Press Enter</button>
</div>
</template>
问题描述
提示:防抖指令传递对应的上下文参数:
一般的防抖
// customDirective.ts
import { App } from 'vue';
export function debounceDirective(app: App) {
app.directive('debounce', {
mounted(el: HTMLElement, binding: any) {
// 初始化定时器变量
let timer: NodeJS.Timeout | null = null;
// 设置默认的防抖延迟时间为 300ms
const defaultDelay = 300;
// 根据 binding.value 的类型确定延迟时间和回调函数
// 如果 binding.value 是数字,则使用它作为延迟时间
// 否则使用默认延迟时间
const delay = typeof binding.value === 'number' ? binding.value : defaultDelay;
// 如果 binding.value 是函数,则使用它作为回调函数
// 否则使用 binding.arg 作为回调函数(假设 binding.arg 是一个函数名)
const callback = typeof binding.value === 'function' ? binding.value : binding.arg;
// 定义处理事件的函数
const handleEvent = () => {
// 如果定时器已经存在,则清除它
if (timer) {
clearTimeout(timer);
}
// 设置新的定时器,在指定的延迟时间后执行回调函数
timer = setTimeout(() => {
// 检查回调函数是否为函数类型
if (typeof callback === 'function') {
// 调用回调函数
callback();
}
}, delay);
};
// 为元素添加点击事件监听器
el.addEventListener('click', handleEvent);
// 为元素添加键盘事件监听器
el.addEventListener('keydown', (event: KeyboardEvent) => {
// 根据修饰符判断触发条件
if (binding.modifiers.enter && event.key === 'Enter') {
// 如果修饰符是 .enter 且按键是 Enter,则调用 handleEvent
handleEvent();
} else if (binding.modifiers.up && event.key === 'ArrowUp') {
// 如果修饰符是 .up 且按键是 ArrowUp,则调用 handleEvent
handleEvent();
} else if (binding.modifiers.down && event.key === 'ArrowDown') {
// 如果修饰符是 .down 且按键是 ArrowDown,则调用 handleEvent
handleEvent();
}
});
}
});
}
注册命令
//index.ts
import type { App } from 'vue';
import {debounceDirective } from '/@/directive/customDirective';
/**
* 导出指令方法:v-xxx
* @methods debounceDirective 防抖指令,用法:v-debounce="{time:500,immediate:true}"
*/
export function directive(app: App) {
// 防抖指令
debounceDirective(app);
}
//main.ts
import { directive } from '/@/directive/index';
directive(app);
原因分析:
提示:这里填写问题的分析:
不满足传参需求于是改进如下
解决方案:
提示:这里填写该问题的具体解决方案:扩写参数
export function debounceDirective(app: App) {
app.directive('debounce', {
mounted(el: HTMLElement, binding: DirectiveBinding) {
let timer: NodeJS.Timeout | null = null;
const defaultDelay = 300; // 默认防抖时间间隔为 300ms
const delay = typeof binding.value === 'object' && 'delay' in binding.value ? binding.value.delay : defaultDelay;
const callback = typeof binding.value === 'object' && 'handler' in binding.value ? binding.value.handler : binding.value;
const handleEvent = (...args: any[]) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
if (typeof callback === 'function') {
// 使用 call 绑定上下文并传递参数
callback.call(binding.instance.proxy, ...args, binding.value.params);
}
}, delay);
};
el.addEventListener('click', handleEvent);
el.addEventListener('keydown', (event: KeyboardEvent) => {
if (binding.modifiers.enter && event.key === 'Enter') {
handleEvent(event);
} else if (binding.modifiers.up && event.key === 'ArrowUp') {
handleEvent(event);
} else if (binding.modifiers.down && event.key === 'ArrowDown') {
handleEvent(event);
}
});
}
});
}
使用 call 绑定上下文并传递参数
。
<!-- index.vue -->
<template>
<div>
<button v-debounce.enter="{ handler: handleKeyPress, params: { message: 'Hello, World!', count: 1 } }">Press Enter</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const handleKeyPress = (event: KeyboardEvent, params: { message: string, count: number }) => {
console.log(params.message); // 输出: Hello, World!
console.log(params.count); // 输出: 1
console.log(event); // 输出: 事件对象
};
</script>
动态上下文
提示:动态上下文传参不适合有延迟,要单独封装成防抖函数使用
/**
* 定义一个类型别名 DebouncedFunction,它代表一个带有 cancel 方法的函数类型
* 这个类型用于扩展原始函数类型 T,使其支持取消操作
*
* @template T 扩展的原始函数类型
*/
type DebouncedFunction<T extends (...args: any[]) => any> = T & { cancel: () => void };
/**
* 创建一个防抖函数,该函数会在最后一次调用 delay 毫秒后执行
* 如果在 delay 毫秒内再次调用该函数,则会重新计算延迟
*
* @template T 原始函数类型
* @param func 要进行防抖处理的原始函数
* @param delay 防抖延迟,单位为毫秒
* @returns 返回一个防抖函数,它可以在调用期间取消执行
*/
const debounce = <T extends (...args: any[]) => any>(func: T, delay: number): DebouncedFunction<T> => {
// 定义一个定时器变量,用于存储 setTimeout 的引用
let timer: NodeJS.Timeout | null = null;
// 定义防抖函数,它会接收与原始函数相同的参数
const debouncedFunc = function (this: ThisParameterType<T>, ...args: Parameters<T>): void {
// 如果定时器存在,则取消之前的定时器,以重新计算延迟
if (timer) clearTimeout(timer);
// 设置一个新的定时器,在指定延迟后执行原始函数
timer = setTimeout(() => {
try {
// 使用 apply 方法调用原始函数,并传递正确的上下文和参数
func.apply(this, args);
} catch (error) {
// 捕获并处理原始函数执行时可能抛出的错误
console.error('Debounced function error:', error);
}
}, delay);
};
// 为防抖函数添加一个 cancel 方法,用于取消尚未执行的函数调用
debouncedFunc.cancel = () => {
// 如果定时器存在,则取消定时器
if (timer) clearTimeout(timer);
// 重置定时器状态
timer = null;
};
// 返回带有 cancel 方法的防抖函数
return debouncedFunc as DebouncedFunction<T>;
};
欢迎点赞评论加收藏