This repository has been archived by the owner on Apr 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
vue2-ajax-form.vue
103 lines (103 loc) · 3.22 KB
/
vue2-ajax-form.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<template>
<form :action="action" :method="method" :enctype="enctype" @submit.prevent="handleAjaxFormSubmit">
<slot></slot>
</form>
</template>
<script lang="babel">
export default {
props: {
'action' : {
type : String,
required: true
},
'method': {
type: String,
default() {
return 'POST'
}
},
'enctype': {
type: String,
default() {
return 'multipart/form-data'
}
},
'responsetype': {
type: String,
default() {
return 'json'
}
},
'before': {
type: Function,
default() {
return function(){}
}
},
'error': {
type: Function,
default() {
return function(){}
}
},
'complete': {
type: Function,
default() {
return function(){}
}
},
'progress': {
type: Function,
default() {
return function(){}
}
},
'after': {
type: Function,
default() {
return function(){}
}
}
},
methods: {
handleAjaxFormSubmit () {
this.before()
var handleError = err => {
this.error(err)
}
if (!this.method) {
this.method = 'post'
}
// eslint-disable-next-line
var xhr = new XMLHttpRequest()
var handleFinish = () => {
if (xhr.readyState === 4) {
if (xhr.status < 400) {
this.complete(xhr.response)
} else {
this.error(xhr.statusText)
}
}
}
var handleProgress = evt => {
if (evt.lengthComputable) {
evt.percent = evt.loaded / evt.total * 100
this.progress(evt)
}
}
xhr.open(this.method, this.action, true)
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.setRequestHeader('Authorization', 'Basic dGVzdDpwYXNzd2Q=')
xhr.responseType = this.responsetype
if (xhr.upload) xhr.upload.addEventListener('progress', handleProgress)
xhr.addEventListener('readystatechange', handleFinish)
xhr.addEventListener('error', handleError)
xhr.addEventListener('abort', handleError)
// eslint-disable-next-line
var data = new FormData(event.target)
xhr.send(data)
this.after()
}
}
}
</script>