用vue+vant实现一个发送短信验证码组件
<template>
<van-button type="primary" :disabled="disabled" @click.stop="startCountDown">{{message || initTip}}</van-button>
</template>
<script>
export default {
data () {
return {
count_time:this.time,
disabled:false,
message:'',
interval:null
}
},
props:{
/** 需要倒数的时间 */
time:{
type:Number,
default:60
},
/** 初始化提示 */
initTip:{
type:String,
default:'发送验证码'
},
/** 倒计时结束时的提示*/
endTip:{
type:String,
default:'重新获取'
},
/** 倒计时开始后 秒数的后缀*/
sufTip:{
type:String,
default:'秒后重新获取'
},
/** 一个异步方法 回调后开始倒计时*/
start:{
type:Function,
required:true
}
},
methods:{
handelClick() {
this.start.then(() => this.startCountDown()).catch(()=>{})
},
startCountDown() {
this.disabled = true
this.interval = setInterval(() => {
if(this.count_time > 1) {
this.count_time --
this.message = this.count_time + this.sufTip
}else {
clearInterval(this.interval)
this.count_time = this.time
this.message = '重新发送'
this.disabled = false
}
},1000)
}
}
}
</script>
<style>
</style>
父组件使用:
<template>
<div class="home">
<van-cell-group>
<van-field label="图片验证码" placeholder="请输入图片验证码" v-model="code" center clearable>
<count-down-btn slot="button" :start="sendCode"></count-down-btn>
</van-field>
</van-cell-group>
</div>
</template>
<script>
import countDownBtn from '@/components/countDownBtn.vue'
export default {
name: 'home',
components: {countDownBtn},
data () {
return {
code:''
}
},
mounted () {},
methods:{
sendCode () {
return new Promise((resolve,reject) => {
if(!this.code) {
alert('请输入手机号')
reject()
}else {
//发送短信验证码接口
resolve()
}
})
}
}
}
</script>
<style>
*{
margin: 0;
padding: 0;
}
.home{
width: 100%;
}
</style>