problem background: when using vee-validate, it is necessary to detect whether the user input value already exists through ajax in real time. An asynchronous detection rule is defined and event throttling is used
because of event throttling, I extract the detection function and want to pass it by saving the parameters in this, but the result is not what I thought
async function check() {
const res = await Vue.prototype.$api.checkIfParamsValueExist(this.key, this.value)
let valid = res ? res.info : true
this.resolve({
valid,
data: valid ? "" : { message: "" }
})
}
Validator.extend("notExist", {
getMessage: (field, params, data) => {
return (data && `${field} ${data.message}`) || "Something went wrong";
},
validate: (value, [key]) => {
return new Promise(resolve => {
console.log(value)
this.value = value
this.key = key
this.resolve = resolve
console.log("resolve", resolve)
throttle(check, this, 800)
})
}
});
when validating the form, v is always in pending and cannot be executed into then, but I have already resolve it above
const v = this.$validator.validateAll()
console.log(v)
v.then((result) => {
console.log("validateAll result", result)
})
it will work well if I directly define the check function when passing parameters to the throttle function, but then the throttle function will not work
Validator.extend("notExist", {
getMessage: (field, params, data) => {
return (data && `${field} ${data.message}`) || "Something went wrong";
},
validate: (value, [key]) => {
return new Promise(resolve => {
throttle(async function() {
const res = await Vue.prototype.$api.checkIfParamsValueExist(key, value)
console.log(res)
let valid = res ? res.info : true
resolve({
valid,
data: valid ? "" : { message: "" }
})
}, this, 800)
})
}
});
event throttling function is attached
function throttle(method, context, time = 100) {
if (method.tId) {
return
}
method.tId = setTimeout(() => {
method.call(context)
clearTimeout(method.tId)
method.tId = 0
}, time)
}