<template>
<van-field
v-model="from.code"
center
label="短信验证码"
maxlength="6"
placeholder="请输入短信验证码"
:rules="[{ required: true, }]"
>
<template #button v-if="timeLeft > 0">
<van-button class="timeLeft_text" size="small" type="info">{{ timeLeft }}秒后重试</van-button>
</template>
<template #button v-else>
<van-button size="small" @click="sendVerificationCode" class="code_text">发送验证码</van-button>
</template>
</van-field>
</template>
<script>
export default {
data() {
return {
from: {
phone: '',
code: ''
},
timeLeft: 0,
}
},
methods: {
//发送验证码
sendCode() {
let params = { phone: this.from.phone };
getAction("接口地址", params).then(res => {
if (res.data.success) {
this.$toast(res.data.message);
} else {
this.$toast(res.data.message);
this.timeLeft = 0;
}
});
},
sendVerificationCode() {
const phoneRege = /^1[3-9]\d{9}$/
if (!phoneRege.test(this.from.phone)) {
return this.$toast('手机号不正确')
}
if (this.timeLeft > 0) {
return;
}
this.sendCode();
this.timeLeft = 60;
let interval = setInterval(() => {
this.timeLeft--;
if (this.timeLeft <= 0) {
clearInterval(interval);
}
}, 1000);
}
}
}
</script>
自己整理的笔记 也是可以直接复用