1、父组件 home.vue
<template>
<div>
<SendTime
:type="type"
:maxCount="count"
:disabled="disabled"
@successChange="sendChange"
ref="SendTime"
/>
</div>
</template>
<script>
import SendTime from "../components/sendTime/index.vue";
export default {
components: { SendTime },
data() {
return {
type:'phone',
count:60,
disabled:false
};
},
methods:{
sendChange(){
console.log('发送验证码成功返回的状态')
}
}
};
</script>
2、子组件 sendTime.vue
<template>
<div
class="send_time"
:class="{send_disabled: disabled }"
@click="sendTime"
>
<span class="send_count" v-if="timeCount"
>{{ timeCount }}s </span
>{{ msgTitle }}
</div>
</template>
<script>
export default {
props: {
// 类型
type: {
type: String,
required: true,
}, //倒计时数
maxCount: {
type: Number,
default: 60,
}, //是否禁用
disabled: {
type: Boolean,
default: false,
},
},
data() {
return {
isLoading: false,
isStart: false,
timeCount: 0,
};
},
computed: {
msgTitle() {
if (this.timeCount) {
return "后重新发送";
}
if (this.isStart) {
return "重新发送";
}
return "获取验证码";
},
},
methods: {
sendTime() {
if (this.disabled) {
return;
}
if (this.timeCount) {
return;
}
// setTimeout代替调用接口,将后端返回的数据通过$emit传给父组件
setTimeout(() => {
this.startLoop();
this.$emit("successChange");
this.verbifyType();
}, 1000);
},
verbifyType() { //给出提示是什么验证码
if (this.type === "email") {
console.log("邮箱验证码已发送,注意查收");
} else {
console.log("手机验证码已发送,注意查收");
}
},
// 清除倒计时
clearTimer() {
if (this.$options.__tmp_timer) {
clearTimeout(this.$options.__tmp_timer);
this.$options.__tmp_timer = null;
}
},
// 倒计时
startLoop() {
this.clearTimer();
this.timeCount = this.maxCount;
if (!this.isStart) {
this.isStart = true;
}
const loopTime = (num) => {
if (num === 0) {
this.clearTimer();
return;
}
this.$options.__tmp_timer = setTimeout(() => {
let _num = num - 1;
this.timeCount = _num;
loopTime(_num);
}, 1000);
};
loopTime(this.timeCount);
},
},
destroyed() {
this.clearTimer();
},
};
</script>
<style scoped>
.send_time {
font-size: 14px;
font-weight: 400;
color: #3300be;
text-decoration: underline;
position: relative;
text-align: center;
cursor: pointer;
}
.send_count{
color: red;
}
.send_disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>```