项目中写了很多短信验证码倒计时,不过这个是我写过的代码最优的,记录下,代码直接复制到项目即可,样式根据项目需求自己调一下即可,功能是完整的,记录下,下次项目中用到直接复制即可
1<el-button :disabled="isDisabled" size="small" type="primary" @click="getIdentifyCodeBtn">
2{{ isDisabled ? count + 's后获取' :click }}
3 </el-button>
4data() {
5 return {
6 count: "59",
7 click: "获取短信验证码",
8 isDisabled: false,
9 }
10},
11methods: {
12 //验证码
13 getIdentifyCodeBtn() {
14 if (!this.globalPhoneReg.test(this.uphone)) {
15 this.$message({
16 showClose: true,
17 message: '手机号格式不正确',
18 type: 'error'
19 });
20 return false;
21 }
22 getIdentifyCode({
23 phoneNumber: this.uphone,
24 language: this.$store.state.language,
25 }).then((result) => {
26 const {code, data} = result;
27 if (code == 200) {
28 this.countTime();//200才需要发送验证码,发送手机短信后倒计时便开启
29 this.$message({
30 showClose: true,
31 message: '短信验证码发送成功',
32 type: 'success'
33 });
34 }
35 });
36 },
37 // 倒计时
38 countTime() {
39 const TIME_COUNT = 60; //倒计时60秒
40 if (!this.timer) {
41 this.count = TIME_COUNT;
42 this.isDisabled = true;
43 this.timer = setInterval(() => {
44 if (this.count > 0 && this.count <= TIME_COUNT) {
45 this.count--;
46 } else {
47 this.isDisabled = false;
48 clearInterval(this.timer);
49 this.timer = null;
50 }
51 }, 1000);
52 }
53 },
54}