vue自定义指令 防抖 vue3 ts

vue自定义指令 防抖

vue指令基础

1.新建一个 instructions,ts js版本请自行修改

2 复制粘贴下面代码

class Instructions {
    public app : any = "";

    public init(app : any) {
        this.app = app;
        this.debounce();
    };

    // 防抖
    private debounce() {
        this.app.directive('dzs-debounce', {
            bind(el : any, binding : any) {
                let debounceTime = binding.value; // 防抖时间
                if (!debounceTime) { // ⽤户若不设置防抖时间,则默认.5s
                    debounceTime = 500;
                }
                let timer:any = null;
                el.addEventListener('click', (event : any) => {
                    if (!timer) { // 第⼀次执⾏
                        cbFun = setTimeout(() => {
                            timer = null;
                        }, debounceTime);
                    } else {
                        event && event.stopImmediatePropagation();
                    }
                }, true);
            },
        })
    }
}

export default new Instructions();

3.在main.ts 导入 instructions,ts

import instructions from "./utils/instructions" ;

4.初始化指令

// 初始化指令
instructions.init(app);

5.在html中使用指令就可以了

<div v-dzs-open>
    xxxxxxx
div>

<div v-dzs-debounce>div>

防抖参考

点我跳转

你可能感兴趣的:(vue.js,typescript,javascript)