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` 的值 */
}
相关推荐
kyriewen111 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
摇滚侠2 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
Timer@3 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫3 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81633 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan5 小时前
FastAPI -API Router的应用
前端·网络·python
走粥6 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0016 小时前
layui select重新渲染
前端·layui
weixin199701080166 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化