Skip to content

Commit cf1aae2

Browse files
EnEn
authored andcommitted
vue get sms code component
1 parent a8758bb commit cf1aae2

File tree

1 file changed

+70
-5
lines changed

1 file changed

+70
-5
lines changed

src/vue-get-code.vue

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,80 @@
11
<template>
2-
<div class="vue-get-code" v-bind="$attrs" v-on="$listeners">
3-
hello
4-
</div>
2+
<span
3+
class="vue-get-code"
4+
v-bind="$attrs"
5+
:class="[disable && 'disable', enableCountdown && 'enable-countdown']"
6+
v-on="$listeners"
7+
@click="click"
8+
>
9+
<slot v-if="!enableCountdown" name="default">获取验证码</slot>
10+
<slot v-if="enableCountdown" name="countdown" :data="{interval, seconds}"
11+
>{{ interval - seconds }}S</slot
12+
>
13+
</span>
514
</template>
615

716
<script>
817
export default {
918
name: 'VueGetCode',
10-
props: {},
19+
props: {
20+
getCode: {
21+
required: true,
22+
type: Function
23+
},
24+
interval: {
25+
default: 60,
26+
type: Number
27+
},
28+
// 让外部调用者能控制组件的禁用状态,比如,如果没填手机号码,获取验证码的按钮要禁用
29+
disable: {
30+
default: false,
31+
type: Boolean
32+
}
33+
},
1134
data() {
12-
return {}
35+
return {
36+
timer: null,
37+
seconds: 0,
38+
enableCountdown: false
39+
}
40+
},
41+
watch: {
42+
disable(newValue) {
43+
// 倒计时正在运行,外部突然禁用了,就清理计时器等状态
44+
if (newValue && this.timer) {
45+
this.reset()
46+
}
47+
}
48+
},
49+
destroyed() {
50+
this.reset()
51+
},
52+
methods: {
53+
async click() {
54+
if (this.enableCountdown) return
55+
if (this.disable) return
56+
57+
this.seconds = 0
58+
this.enableCountdown = true
59+
this.timer = setInterval(() => {
60+
this.seconds++
61+
62+
if (this.seconds >= this.interval || this.disable) {
63+
this.reset()
64+
}
65+
}, 1000)
66+
67+
await this.getCode().catch(() => {
68+
alert('ca')
69+
this.reset()
70+
})
71+
},
72+
reset() {
73+
clearInterval(this.timer)
74+
this.timer = null
75+
this.seconds = 0
76+
this.enableCountdown = false
77+
}
1378
}
1479
}
1580
</script>

0 commit comments

Comments
 (0)