文章目錄
- 代碼
- 參數講解
在寫項目時,總會有要進行防抖節流的時候,如果寫一個debounce函數的話 用起來代碼總會是有點長的,因此想到了用一個全局指令進行輸入框的防抖,畢竟全局指令使用時只要v-xxx就行了,非常方便
代碼
前提是需要全局注冊
使用
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函數的幾個參數
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 鉤子中可用。
舉個例子
<div v-example:foo.bar="baz">
binding參數會是一個這樣的對象
{arg: 'foo',modifiers: { bar: true },//傳遞的修飾符value: /* `baz` 的值 */,oldValue: /* 上一次更新時 `baz` 的值 */
}