美文网首页ts
装饰器 - 防抖

装饰器 - 防抖

作者: johnnie_wang | 来源:发表于2020-07-04 17:31 被阅读0次
    // decorators.js
    import { createDecorator } from 'vue-class-component'
    
    export type DebounceOptions =
      | number
      | {
          time: number
        }
    
    export function Debounce(options: DebounceOptions): any {
      return createDecorator((opts:any, handler:any) => {
        if (!opts.methods) throw new Error('This decorator must be used on a vue component method.')
    
        const time = typeof options === 'number' ? options : options.time
    
        const originalFn = opts.methods[handler]
        let timeoutId:any = 0
    
        const clear = () => {
          if (timeoutId) {
            clearTimeout(timeoutId)
            timeoutId = 0
          }
        }
    
        opts.methods[handler] = function(...args: any[]) {
          clear()
          timeoutId = setTimeout(() => {
            timeoutId = 0
            originalFn.apply(this, args)
          }, time)
        }
      })
    }
    
    

    使用

    import { Debounce } from '@/utils/decorators'
    
    \\ 2. 使用 @Debounce 装饰你的事件回调函数,参数为:多少ms后执行
    
     @Debounce(1000)
     foo(){
     }
    

    复制直接用~

    相关文章

      网友评论

        本文标题:装饰器 - 防抖

        本文链接:https://www.haomeiwen.com/subject/geouqktx.html