File tree Expand file tree Collapse file tree 1 file changed +70
-5
lines changed Expand file tree Collapse file tree 1 file changed +70
-5
lines changed Original file line number Diff line number Diff line change 1
1
<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 >
5
14
</template >
6
15
7
16
<script >
8
17
export default {
9
18
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
+ },
11
34
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
+ }
13
78
}
14
79
}
15
80
</script >
You can’t perform that action at this time.
0 commit comments