/
FormElementMixin.js
130 lines (117 loc) · 3.59 KB
/
FormElementMixin.js
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import config from '../utils/config'
export default {
props: {
size: String,
expanded: Boolean,
loading: Boolean,
rounded: Boolean,
icon: String,
iconPack: String,
// Native options to use in HTML5 validation
autocomplete: String,
maxlength: [Number, String]
},
data() {
return {
isValid: true,
isFocused: false,
newIconPack: this.iconPack || config.defaultIconPack
}
},
computed: {
/**
* Find parent Field, max 3 levels deep.
*/
parentField() {
let parent = this.$parent
for (let i = 0; i < 3; i++) {
if (parent && !parent.$data._isField) {
parent = parent.$parent
}
}
return parent
},
/**
* Get the type prop from parent if it's a Field.
*/
statusType() {
if (!this.parentField) return
if (!this.parentField.newType) return
if (typeof this.parentField.newType === 'string') {
return this.parentField.newType
} else {
for (let key in this.parentField.newType) {
if (this.parentField.newType[key]) {
return key
}
}
}
},
/**
* Get the message prop from parent if it's a Field.
*/
statusMessage() {
if (!this.parentField) return
return this.parentField.newMessage
},
/**
* Fix icon size for inputs, large was too big
*/
iconSize() {
switch (this.size) {
case 'is-small': return this.size
case 'is-medium': return
case 'is-large': return this.newIconPack === 'mdi'
? 'is-medium'
: ''
}
}
},
methods: {
/**
* Focus method that work dynamically depending on the component.
*/
focus() {
if (this.$data._elementRef === undefined) return
this.$nextTick(() => this.$el.querySelector(this.$data._elementRef).focus())
},
onBlur($event) {
this.isFocused = false
this.$emit('blur', $event)
this.checkHtml5Validity()
},
onFocus($event) {
this.isFocused = true
this.$emit('focus', $event)
},
/**
* Check HTML5 validation, set isValid property.
* If validation fail, send 'is-danger' type,
* and error message to parent if it's a Field.
*/
checkHtml5Validity() {
if (this.$refs[this.$data._elementRef] === undefined) return
const el = this.$el.querySelector(this.$data._elementRef)
let type = null
let message = null
let isValid = true
if (!el.checkValidity()) {
type = 'is-danger'
message = el.validationMessage
isValid = false
}
this.isValid = isValid
if (this.parentField) {
// Set type only if not defined
if (!this.parentField.type) {
this.parentField.newType = type
}
// Set message only if not defined
if (!this.parentField.message) {
this.parentField.newMessage = message
}
}
return this.isValid
}
}
}