一、效果展示
二、代码部分
1、html部分
<el-form-item label="手机号" prop="phone"><el-input style="width: 320px" v-model="regForm.phone" clearable></el-input></el-form-item><el-form-item label="验证码" prop="code"><el-input style="width: 320px" v-model="regForm.code" clearable><el-buttonslot="suffix"style="color: blue;float: right":disabled="disabled"@click="getCode">{{btnTxt}}</el-button></el-input></el-form-item>
2、vue.js部分
<script>import instance from "../utils/request";export default {name: "register",data() {let validatePhone = (rule,value,callback)=>{/*console.log(rule);console.log(value);console.log(callback);*/if (!value){callback(new Error('手机号不能为空'));}//使用正则表达式进行验证手机号码if (!/^1[3456789]\d{9}$/.test(value)){callback(new Error('手机号不正确'));}//自定义校验规则 需要调用callback()函数!callback();};return {//验证码部分所需的数据btnTxt:"获取验证码",disabled:false,time:0,regForm: {}, // 注册表单对象code: '', // 验证码rules: {username: [{required: true, message: '请输入用户名', trigger: 'blur' },{min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],password: [{required: true, message: '请输入密码', trigger: 'blur' }],phone: [{required: true, validator: validatePhone, trigger: 'blur' }],code: [{required: true, message: '请输入验证码', trigger: 'blur' }],}};},methods: {//获取手机验证码方法getCode(){//1.校验手机号码if (!this.regForm.phone){//手机号校验不通过this.$message({message: '请输入手机号码!',type: 'warning',});}else if (!/^1[3456789]\d{9}$/.test(this.regForm.phone)){//此处失去焦点后自动触发校验手机号规则}else {//2.【手机号码校验通过】发送axios请求 获取验证码this.time = 30; //设置倒计时的时间(单位:秒)this.disabled = true;this.timer();//调用倒计时方法instance.get('/user/getCode?phone=' + this.regForm.phone).then(res=>{console.log(this.regForm.phone);if (res.data.state){//短信验证码发送成功时的消息提示this.$message({message: res.data.msg,type: 'success',});}else {//短信验证码发送失败时的消息提示this.$message({message: res.data.msg,type: 'warning',});}})}},//倒计时方法timer() {if (this.time > 0) {this.time--;console.log(this.time);this.btnTxt = this.time+ "s后重新获取验证码";setTimeout(this.timer, 1000);} else{this.time = 0;this.btnTxt = "获取验证码";this.disabled = false;}},}}</script>