关键代码
<el-form ref="registerFormRef" :model="registerForm" status-icon :rules="registerRules" label-width="70px">
<el-form-item label="手机号" prop="tel">
<el-input v-model="registerForm.tel" autocomplete="off" placeholder="请输入手机号" />
<el-link type="danger" @click="sendCode" :disabled="hasBeenSend">{{ sendCodeText }}</el-link>
</el-form-item>
</el-form>
<script lang="ts">
import { defineComponent, reactive, toRefs, unref, ref, onMounted, watch } from "vue";
import { FormInstance } from "element-plus";
export default defineComponent({
setup() {
const registerFormRef = ref<FormInstance>();
const telValidator = (rule, value, callback) => {
if (!value) {
callback(new Error("请输入手机号"));
} else if (!/^1[3456789]\d{9}$/.test(value)) {
callback(new Error("手机号格式不正确"));
} else {
callback();
}
};
const registerRules = {
tel: [
{
validator: telValidator,
trigger: "blur",
required: true,
},
],
}
const sendCode = () => {
const formRef: any = unref(registerFormRef);
formRef.validateField("tel", (valid: boolean) => {
if (valid) {
let timer = setInterval(() => {
if (initData.countDown > 0) {
initData.hasBeenSend = true;
initData.countDown--;
initData.sendCodeText = initData.countDown + "秒后重新获取";
} else {
initData.hasBeenSend = false;
initData.countDown = 60;
initData.sendCodeText = "重新获取";
clearInterval(timer);
}
}, 1000);
sendCodeApi(initData.registerForm.tel);
}
});
};
return {
registerRules,
registerFormRef,
};
}
</script>
效果展示
|