装饰器 - 防抖

// 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(){
 }

复制直接用~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。