vue3定义全局防抖指令

文章目录

在写项目时,总会有要进行防抖节流的时候,如果写一个debounce函数的话 用起来代码总会是有点长的,因此想到了用一个全局指令进行输入框的防抖,毕竟全局指令使用时只要v-xxx就行了,非常方便

代码

前提是需要全局注册

使用

javascript 复制代码
export default {
  debounce: {
    mounted(
      el: {
        addEventListener: (arg0: string, arg1: () => void) => void;
        value: any;
      },
      binding: { value: any; arg: any },
    ) {
      let timer: number | null = null;
      const { value, arg = 0 } = binding;
  

      el.addEventListener("input", () => {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          value(el.value, arg);
        }, 1000);
      });
    },
    updated(
      el: {
        addEventListener: (arg0: string, arg1: (e: any) => void) => void;
        value: any;
        removeEventListener: (arg0: string, arg1: (e: any) => void) => void;
      },
      binding: { value: any; arg: any },
    ) {
      // 若指令的值更新,重新绑定事件处理函数
      let timer: number | null = null;
      let { value, arg = 0 } = binding;
      const existingListener = (e: any) => {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          value(el.value, arg);
        }, 1000);
      };
    //   el.removeEventListener("input", existingListener);
    //   el.addEventListener("input", existingListener);
    },
  },
};

v-debounce 后面的 :[typeId]就是传的参数 即arg

注意:如果写v-debounce.typeId 那么传的就是一个字符串"typeId" 而且[ ]只支持传一个参数 如果想要传多个参数的话 建议使用数组进行整体的传参

参数讲解

讲一下binding函数的几个参数

javascript 复制代码
  bind(el, binding, vnode, oldVnode) { }

el:指令绑定的元素的DOM。

binding:一个传参对象,包含以下的属性:

value:传递给指令的值。例如:v-focus="1",获取到的值就是 1

oldValue:更新之前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否更改,它都可用。

arg:传递给指令的参数 (如果有的话)。例如在

v-my-directive:foo 中,参数是 "foo"。

modifiers:传入修饰符的对象 。例如在v-my-directive.foo.bar 中,修饰符对象是 { foo: true, bar: true }。

instance:使用该指令的组件实例。

dir:指令的定义对象。

vnode:代表绑定元素的底层 VNode。

prevNode:之前的渲染中代表指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。

举个例子

javascript 复制代码
<div v-example:foo.bar="baz">

binding参数会是一个这样的对象

javascript 复制代码
{
  arg: 'foo',
  modifiers: { bar: true },//传递的修饰符
  value: /* `baz` 的值 */,
  oldValue: /* 上一次更新时 `baz` 的值 */
}
相关推荐
崔庆才丨静觅27 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax