简单写一下html部分
<el-form
ref="registform"
:model="registerForm"
:rules="registerRules"
>
<el-form-item prop="phone">
<el-input
ref="phone"
v-model="registerForm.phone"
placeholder="请输入手机号"
name="phone"
type="text"
/>
</el-form-item>
<el-button
native-type="button"
@click="handleGetCode"
:disabled="!canGetCode"
>{{ getCodeBtn.btnText }}
</el-button>
</el-form>
js部分
<script>
import { sendcode } from "@/api/register" // 引入获取验证码的api
import { validatePhone ,validateCode } from "@/utils/validate" //验证规则
export default {
name: 'Register',
data() {
return {
getCodeBtn: {
timer: null,
seconds: 60,
btnText: '获取验证码',
},
registerForm:{
phone:"",
code:""
},
registerRules:{
phone:[
{
validator: validatePhone,
message: "", //验证错误时的提示文字
trigger: "blur",
},
],
code:[
{
validator: validateCode,
message: "",
trigger: "blur",
},
]
}
};
},
computed: {
canGetCode() {
return this.getCodeBtn.btnText === '获取验证码';
},
},
methods: {
async handleGetCode() {
if (!this.registerForm.phone) {
this.$message({
message: '手机号不能为空',
type: "warning",
});
return false;
}
try{
const data = { phone:this.registerForm.phone }
const {code} = await sendcode(data)
if (code === 200) {
this.$message({
message: "验证码发送成功!",
type: "success",
});
// 请求成功后 改变按钮文字
this.initgetCodeTimer();
}
}catch(err){
window.console.error(err);
}
},
initgetCodeTimer() {
if (this.getCodeBtn.timer) {
window.clearInterval(this.getCodeBtn.timer);
this.getCodeBtn.timer = null;
}
let count = this.getCodeBtn.seconds;
this.getCodeBtn.btnText = `重新获取(${count})`;
this.getCodeBtn.timer = window.setInterval(() => {
count--;
if (count === 0) {
if (this.getCodeBtn.timer) {
window.clearInterval(this.getCodeBtn.timer);
this.getCodeBtn.timer = null;
this.getCodeBtn.btnText = '获取验证码';
}
return;
}
this.getCodeBtn.btnText = `重新获取(${count})`;
}, 1000);
},
},
};
</script>