WishMeLz

生活其实很有趣

createDecorator 自定义装饰器

二次确认

import { MessageBox } from 'element-ui'
import { createDecorator } from 'vue-class-component'

export function Confirm(msg: any) {
    return createDecorator(function (opts, handler) {
        if (!opts.methods)
            throw new Error(
                'This decorator must be used on a vue component method.',
            )

        const originalFn = opts.methods[handler]
        opts.methods[handler] = function (...args) {
            // debugger
            if (args[0]?.stopPropagation) {
                args[0].stopPropagation()
            }
            MessageBox.confirm('msg', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: ' 取消',
                customClass: 'msgConfirm',
                callback(type: string) {
                    if (type === 'confirm') {
                        originalFn.apply(_this, args)
                    }
                },
            })
        }
    })
}

节流

export function Throttle(delay: number = 1000, isImmediate: boolean = false) {
    let lastCall = 0
    return createDecorator(function (opts, handler) {
        if (!opts.methods)
            throw new Error(
                'This decorator must be used on a vue component method.',
            )

        const originalFn = opts.methods[handler]

        opts.methods[handler] = function () {
            const _this = this
            const args: any = []
            for (let _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i]
            }

            const now = new Date().getTime()
            if (now - lastCall < delay) {
                return
            }
            lastCall = now
            originalFn.apply(_this, args)
        }
    })
}

防抖

export function Debounce(delay: number = 1000) {
    return createDecorator(function (opts, handler) {
        if (!opts.methods)
            throw new Error(
                'This decorator must be used on a vue component method.',
            )

        const originalFn = opts.methods[handler]
        let timeoutId: null | NodeJS.Timeout = null
        const clear = function () {
            if (timeoutId) {
                clearTimeout(timeoutId)
                timeoutId = null
            }
        }
        opts.methods[handler] = function () {
            const _this = this
            const args: any = []
            for (let _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i]
            }
            clear()
            timeoutId = setTimeout(function () {
                timeoutId = null
                originalFn.apply(_this, args)
            }, delay)
        }
    })
}