Problem Description:
After clicking to send the verification code, in order to make the logic more rigorous, the form verification that comes with the vant component is used to perform a second verification to prevent the login mobile phone number from being modified twice after the verification code is sent successfully, but according to the official website description cv It doesn't take effect, and even the countdown after getting the verification code doesn't go away...
code show as below:
// Get verification code
const getCode = async () => {
// throttling: if time > 0, do not execute
if (time.value > 0) return
time.value = 10
const res = await getLoginCode(mobile.value, 'login')
console.log(res, 'get verification code')
code.value = res.data.code
// Vant's built-in form verification prevents the mobile phone number from being modified again after the verification code is obtained, and prevents the execution of console.log(formRef.value, 'fromRef') if the verification fails againformRef.value?.validate('mobile').catch((error) => {
console.log(error, 'error')
})timeId = setInterval(() => { time.value -= 1 codeText.value = time.value + 's get again after' if (time.value < 1) { codeText.value = 'send verification code' return clearInterval( timeId) } }, 1000) }
The error caught by catch is undefined, that is, the name of the parameter passed by the validate method has no value, and it is found that the name attribute is not added to the structure
The modified code is as follows:
<van-form autocomplete="off" @submit="login" ref="formRef">
<van-field
name="mobile"
v-model="mobile"
:rules="mobileRules"
placeholder="请输入手机号"
type="tel"
></van-field>
Just add the name attribute to the form item that needs to be verified.
Business code optimization:
const getCode = async () => {
// throttling: if time > 0, do not execute
if (time.value > 0) return
time.value = 10
const res = await getLoginCode(mobile.value, 'login')
console.log(res, 'get verification code')
code.value = res.data.code// Vant's built-in form verification prevents the mobile phone number from being modified again after the verification code is obtained, and prevents execution if the verification fails again. // The
return value of validate is a promise, but there is no need to receive the return value here, just add An await is simpler
await formRef.value?.validate('mobile')timeId = setInterval(() => { time.value -= 1 codeText.value = time.value + 's get again after' if (time.value < 1) { codeText.value = 'send verification code' return clearInterval( timeId) } }, 1000) }