组件:
<template>
<el-button type="primary" v-if="!timeCount" @click="sendCode" :disabled="disabled" class="btn">获取验证码</el-button>
<el-button type="primary" v-else disabled class="btn">{{timeCount}}秒后重新获取</el-button>
</template>
<script>
import {getHumanMobileCaptchaApi, getCorpMobileCaptchaApi, getLoginerMobileCaptchaApi} from '@/api/common'
export default {
name: 'countDown',
props: ['disabled', 'transParams'],
data () {
return {
timeCount: 0 // 倒计时
}
},
methods: {
sendCode () {
this.sendSmsCode()
},
sendSmsCode () {
let apiObj = {
addHuman: getHumanMobileCaptchaApi,
addCorp: getCorpMobileCaptchaApi,
modifyPassWord: getLoginerMobileCaptchaApi
}
// 用以接收后端返回的code参数
let codeObj = {
addHuman: 'code',
addCorp: 'code',
modifyPassWord: 'sms_code'
}
let {
type = '', captchatype = '', phone = '', identity_code = '', captcha_id = '', captcha = '', needPhone = true
} = this.transParams
if (needPhone && !/^1[3456789]\d{9}$/.test(phone)) {
this.$message.error(`手机号${phone}格式错误`)
return
}
let params = {}
if (type === 'modifyPassWord') {
params = {
captcha_type: captchatype,
identity_code,
captcha_id,
captcha
}
} else {
params = {
captchatype,
phone
}
}
apiObj[type](params).then(res => {
let {errcode, data} = res
if (errcode === 0 && data) {
this.countTime()
this.$emit('input', data[codeObj[type]])
this.$emit('getaccount', phone)
}
})
},
sendEmailCode () {
let {
needEmail, email, preCheck, codeType, username
} = this.transParams
if (preCheck) {
if (preCheck()) return
}
/* eslint-disable */
var mailreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
/* eslint-enable */
if (needEmail) {
if (!mailreg.test(email)) {
this.$alert({
head: '提示',
msg: `邮箱格式错误`
})
return
}
}
this.countTime()
this.axios.post('page/sendmsgtoemail', {
captchatype: codeType,
email: email,
username: username
}).then((res) => {
let {errcode, data} = res
if (errcode === 0 && data) {
this.$emit('input', data.code)
this.$emit('getaccount', email)
}
}, (e) => {
this.$alert({
head: '提示',
msg: `服务器异常,请稍后再试`
})
})
},
countTime () {
this.timeCount = 60
this.timer = setInterval(() => {
if (--this.timeCount === 0) {
clearInterval(this.timer)
}
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
},
mounted () {
}
}
</script>
<style lang="scss" scoped>
.btn{
width: 140px;
padding: 0 10px;
height: 40px;
}
</style>
使用:
<countDown :transParams="smsCodeParams" :disabled="!phoneActived" v-model.trim="code" @getaccount="getSendPhone"/>
computed: {
smsCodeParams() {
return {
type: 'addHuman',
captchatype: this.type === 'add' ? 'register' : 'modifyphone',
phone: this.formValidate.phone
}
},
}
// 获取验证码
getSendPhone(phone) {
this.getCodePhone = phone
},