-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVForm.vue
86 lines (84 loc) · 3.16 KB
/
VForm.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
<template>
<form :method="method" :action="action" @submit.prevent="submit($event)">
<slot></slot>
<!--<h5 class="text-center" v-if="isSubmitting">Das Formular wird übermittelt.</h5>-->
</form>
</template>
<script>
const SUCCESS_EVENT = 'event';
const SUCCESS_REDIRECT = 'redirect';
export default {
props: {
method: { type: String, default: 'GET' },
action: { type: String, default: '/' },
onSuccess: { default: SUCCESS_EVENT },
},
data() {
return {
isSubmitting: false
}
},
methods: {
submit($event) {
this.hideErrors();
this.toggleIsSubmitting(true);
this.getSubmitButton();
switch(this.method.toLowerCase()) {
case 'get':
axios.get(this.action).then(
response => { this.handleSuccess(response.data) },
errorResponse => { this.showErrors(errorResponse.response.data.errors) }
);
break;
case 'post':
const formData = new FormData($event.target);
axios.post(this.action, formData).then(
response => { this.handleSuccess(response.data) },
errorResponse => {
if(errorResponse.response.data.errors) this.showErrors(errorResponse.response.data.errors)
this.toggleIsSubmitting(false)
}
);
break;
}
},
toggleIsSubmitting(state) {
var formElements = this.$el.elements;
for (var i = 0, len = formElements.length; i < len; ++i) {
formElements[i].readOnly = state;
}
this.isSubmitting = state;
this.getSubmitButton().disabled = state;
},
showErrors(errors) {
this.$emit('error');
this.toggleIsSubmitting(false);
this.getInputs().forEach(input => {
if(errors[input.name]) input.showErrors(errors[input.name])
})
},
hideErrors() {
this.getInputs().forEach(input => {
input.hideErrors()
})
},
getInputs() {
return this.$children.filter((child) => {
return child.$el.children[0] && child.$el.children[0].name;
})
},
getSubmitButton() {
return this.$el.querySelector('[type="submit"]')
},
handleSuccess(response) {
switch (this.onSuccess) {
case SUCCESS_REDIRECT:
window.location.assign(response);
break;
}
this.toggleIsSubmitting(false);
this.$emit('success', response);
}
}
}
</script>