1.结构(结构和css样式可根据自己需要修改)
<input type="number" name="code" maxlength="6" placeholder="请输入验证码" v-model="user.code" />
<button :disabled="disabled" class="t-c" @tap="getCode()">{{title}}</button>
2.js部分
export default {
data() {
return {
second: '', //倒计时
disabled: false, //是否禁用按钮
timer: null, //计时器
user: {
oldPassword: '', //旧密码
password: '', //密码
password2: '', //密码
userName: '', //个人姓名
phone: '', //手机号码
certificationId: '', //身份证号
code: '' //验证码
}
};
},
//计算属性
computed: {
title() {
return this.disabled ? `重新获取 ( ${this.second} ) s` : '获取验证码';
},
},
methods: {
//获取短信验证码
getCode() {
console.log('点击')
let that = this
let s = 60 //倒计时间
if (!that.timer) {
that.second = s
that.disabled = true
that.timer = setInterval(() => {
if (that.second > 0 && this.second <= s) {
that.second--
} else {
that.disabled = false
clearInterval(that.timer)
this.timer = null
}
}, 1000)
}
},
};
- 不建议使用全局定时器,容易出现内存泄漏等问题。
- 推荐使用Vue的watch或
computed
等响应式数据实现倒计时功能。