Vue组件开发之LeanCloud带图形校验码的短信发送功能

2020-06-16 05:56:32易采站长站整理

captcha.bind({
textInput: this.$refs.captcha.$el.children[0],
image: this.$refs.captchaImage,
verifyButton: this.$refs.sendSms.$el
}, {
success: (validateToken) => {
this.$emit('sendSmsCode', validateToken)
},
error: () => {
this.$message.error('请输入正确的图形校验码!')
}
})
})
}

组件使用

首先在父组件的组件选项中添加包含Mobile组件的components,然后在模板中添加mobile组件。


<mobile v-model="mobileForm.mobile"
:sms-sent.sync="mobileForm.smsSent"
@sendSmsCode="sendSms"></mobile>

其中绑定sendSmsCode事件的方法如下:


sendSms (validateToken) {
this.sendSmsCode({
mobile: this.mobileForm.mobile,
validateToken
}).then(() => {
this.mobileForm.smsSent = true
})
},

完整组件代码


<template>
<el-form class="mobile-form"
:label-width="labelWidth"
ref="mobile-form">
<el-form-item label="手机号码" prop="mobile">
<el-input :value="value"
@input="value => $emit('input', value)"
:maxlength="11"
type="tel">
</el-input>
</el-form-item>
<el-form-item label="图形校验码">
<el-input type="text" ref="captcha"></el-input>
<img ref="captchaImage">
</el-form-item>
<el-form-item>
<el-button type="info"
ref="sendSms"
:disabled="smsCodeCountingDown > 0 ||
value.length !== 11">
发送验证码
</el-button>
<span v-if="smsCodeCountingDown > 0">
{{smsCodeCountingDown}} 秒后重新发送
</span>
</el-form-item>
</el-form>
</template>
<script>
import AV from 'leancloud-storage'
export default {
data () {
return {
smsCodeCountingDown: 0
}
},
props: {
labelWidth: {
type: String,
default: '100px'
},
value: String,
smsSent: Boolean
},
watch: {
smsSent (val) {
if (val) {
this.smsCodeCountingDown = 30
let countingDownInterval = setInterval(() => {
this.smsCodeCountingDown--
if (this.smsCodeCountingDown === 0) {
clearInterval(countingDownInterval)
}
}, 1000)
}
}
},
mounted () {
AV.Captcha.request().then((captcha) => {
captcha.bind({
textInput: this.$refs.captcha.$el.children[0],
image: this.$refs.captchaImage,
verifyButton: this.$refs.sendSms.$el
}, {
success: (validateToken) => {
this.$emit('update:smsSent', false)
leancloud this.$emit('sendSmsCode', validateToken)
},