代码如下:

// use-lock-fn.js
import { ref } from 'vue'

// fn 需要增加竞态锁的函数
// autoUnlock === true 不管fn返回什么, 都自动解锁
// autoUnlock === false 不管fn返回什么, 都不自动解锁
// autoUnlock === 'auto' (默认值) 当fn返回false时, 不自动解锁, 返回其他值时, 自动解锁
const useLockFn = (fn = () => {}, autoUnlock = 'auto') => {
    const lock = ref(false)
    return async (...args) => {
        if (lock.value) return
        lock.value = true
        try {
            const $return = await fn(...args)
            if (autoUnlock === true || (autoUnlock === 'auto' && $return !== false)) lock.value = false
        } catch (e) {
            lock.value = false
            throw e
        }
    }
}

export default useLockFn

使用方法:

<template>
    <a @click="handleLogin({ user: '123', pass:'456' })" href="javascript:;">登录</a>
</templaet>
<script>
import useLockFn from './use-lock-fn'

export default {
    setup() {
        const handleLogin = useLockFn(async form => {
            const { code, message } = await api.post('/user/login', form)
            if (code === 200) {
                // 其他逻辑
                // return false
            }
        })

        return {
            handleLogin
        }
    }
}
</script>