vue3 validator校验防抖的问题
const rule = { bucketNameRules() {
const valid = (rule, value) => {
const reg = /^(?![-])[a-z0-9-]{3,63}(?<![-])$/
if (value.length < 3 || value.length > 63) {
return Promise.reject('请输入 3~63 个字符')
} else if (!reg.test(value)) {
return Promise.reject('允许小写字母、数字、短横线(-),且不能以短横线开头或结尾')
}
//调用接口查询是否重复
return bucketNameCheck({
bucketName: value
}).then((res) => {
availableName.value = res.available
if (availableName.value) {
return Promise.resolve()
} else {
return Promise.reject('该Bucket已存在,或被其他用户占用')
}
})
}
return { validator: valid, trigger: 'change', required: true }
}
以上代码是校验规则 和调用接口查询
现在是每次输入都会触发bucketNameCheck方法
麻烦谁能给一个防抖成功的例子,就是输入时不会每次输入都触发bucketNameCheck方法,达到防抖的效果!!谢谢各位大佬了!! vue3+antd2
回答:
网上的各种库都有防抖,我猜你是想返回Promise? 如果直接清定时器可能会有Promise内存释放不掉的问题,所以我写了个abortPromise函数,增加了中断Promise的功能。
type AbortPromise = Promise<unknown> & {abort?: (flag?:boolean) => void}const abortPromise = (promise1: Promise<unknown>) => {
let abort;
const promise2:Promise<unknown> = new Promise((resolve, reject) => {
abort = reject;
})
const p:Promise<unknown> & {abort?: (flag?:boolean) => void} = Promise.race([promise1, promise2]);
p.abort = abort
return p
}
const debouncePromise = (success: (...rest: unknown[]) => Promise<unknown>, fail: (...rest: unknown[]) => Promise<unknown>, time: number):(...rest:unknown[]) => Promise<unknown> => {
let promise: AbortPromise;
return function(...rest) {
if (promise && typeof promise.abort === 'function') {
promise.abort()
}
const timeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve(undefined)
}, time)
})
promise = abortPromise(timeoutPromise)
return promise.then(() => {
return success(...rest);
}).catch(() => {
return fail(...rest);
})
}
}
const success = (...rest:unknown[]) => {
console.log('请求后台接口', rest)
return Promise.resolve('success')
}
const fail = (...rest:unknown[]) => {
console.log('放弃', rest)
return Promise.reject('fail')
}
const handle = debouncePromise(success, fail, 2000)
const clickHandle = () => {
handle('123', '245').then((data) => {
console.log(data)
}).catch(() => {
console.log('放弃')
})
}
以上是 vue3 validator校验防抖的问题 的全部内容, 来源链接: utcz.com/p/937226.html