InputGroup.vue
2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<template>
<div class="input-group">
<template v-for="(i,index) in length">
<div
:key="index"
:class="['input',{'active':values[index]},{'error':error}]"
>
<input
v-model="values[index]"
type="number"
maxlength="1"
@input="input(index,$event)"
:ref="`focus-${index}`"
@keydown="keydown(index,$event)"
>
</div>
</template>
</div>
</template>
<script type='text/ecmascript-6'>
export default {
name: 'InputGroup',
data () {
return {
values: [],
flag: false,
focusList: []
}
},
props: {
length: {
type: Number,
default: 6
},
value: {
type: String,
default: ''
},
error: {
type: Boolean,
default: false
},
pattern: {
type: RegExp
}
},
watch: {
'values' (newVal) {
this.$emit('input', newVal.join(''))
},
},
mounted () {
let { value, length } = this
if (value) {
value = value.substring(0, length)
this.values = value.split('')
} else {
this.values = new Array(6).fill('')
this.focusList = new Array(6).fill(false)
}
},
methods: {
keydown (index, $event) {
let { keyCode } = $event
if (keyCode == 8) {
setTimeout(() => {
if (index > 0) this.$refs[`focus-${index - 1}`][0].focus()
}, 100)
}
},
input (index) {
let { length, pattern } = this
this.values[index] = pattern.test(this.values[index]) ? this.values[index].substring(0, 1) : ''
if (index < length - 1 && this.values[index]) this.$refs[`focus-${index + 1}`][0].focus()
}
}
}
</script>
<style scoped lang='scss'>
.input-group {
display: flex;
.input {
width: 36px;
height: 36px;
background: #ffffff;
border: 1px solid #dbdbdb;
padding: 0 12px;
box-sizing: border-box;
margin-right: 24px;
input {
width: 100%;
height: 100%;
border: none;
}
&:last-of-type {
margin-right: 0;
}
}
.active {
border-color: #008fff;
}
.error {
border-color: #fa5151;
}
}
</style>