-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberInput.vue
89 lines (88 loc) · 1.91 KB
/
NumberInput.vue
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
<template>
<el-input v-model="model" v-bind="$attrs" v-on="listeners">
<slot v-for="(value, key) in $slots" :name="key" :slot="key"></slot>
</el-input>
</template>
<script>
export default {
name: 'NumberInput',
inheritAttrs: false,
props: {
value: {
type: [Number, String],
default: ''
},
type: {
// integer: 整数, decimal: 小数
type: String,
default: 'decimal'
},
signed: {
// plus: 正数, minus: 负数, all: 全部
type: String,
default: 'plus'
},
places: {
//保留小数位数
type: [Number, String],
default: 2 //默认两位小数
}
},
data() {
return {
model: this.value,
temporary: this.value
}
},
computed: {
listeners() {
return { ...this.$listeners, input: this._input }
},
regs() {
return {
'integer-plus': /^\d+$/,
'integer-minus': /^-\d*$/,
'integer-all': /^-?\d*$/,
'decimal-plus': new RegExp(`^\\d+(\\.\\d{0,${this.places}})?$`),
'decimal-minus': new RegExp(`^-(\\d*|\\d+(\\.\\d{0,${this.places}})?)$`),
'decimal-all': new RegExp(`^-?(\\d*|\\d+(\\.\\d{0,${this.places}})?)$`)
}
},
regName() {
return `${this.type}-${this.signed}`
},
reg() {
return this.regs[this.regName]
}
},
watch: {
value(n, o) {
// 新旧值不一样;或者 length 不一样,比如 6 和 06
if (n != o || `${n}`.length !== `${o}`.length) {
this.temporary = n
}
},
temporary(n, o) {
n = n + ''
if (n && !this.reg.test(n)) {
n = o
this.temporary = o
return
}
this.model = n
this.$emit('input', n)
}
},
methods: {
_input(val) {
this.temporary = val
}
},
created() {
const val = this.value + ''
if (val && !this.reg.test(val)) {
this.temporary = ''
}
}
}
</script>