這種方式可以提交,那麼問題來了,表單提交以後如果需要獲取服務器的響應呢,如果需要在響應成功後跳轉頁面呢,這種方式顯得不好處理.
切回正題,在vue中這種簡單的表單提交如何處理呢,其實使用的是 FormData 來模擬表單提交
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
|
< head > < title ></ title > < meta
charset = "UTF-8" > < meta
name = "viewport"
content = "width=device-width,
initial-scale=1" > </ head > < body > < form > < input
type = "text"
value = ""
v-model = "name"
placeholder = "請輸入用戶名" > < input
type = "text"
value = ""
v-model = "age"
placeholder = "請輸入年齡" > < input
type = "file"
@ change = "getFile($event)" > < button
@ click = "submitForm($event)" >提交</ button > </ form > < script > window.onload
= function () { Vue.prototype.$http
= axios; new
Vue({ el:
'form', data:
{ name:
'', age:
'', file:
'' }, methods:
{ getFile(event)
{ this.file
= event.target.files[0]; console.log(this.file); }, submitForm(event)
{ event.preventDefault(); let
formData = new FormData(); formData.append('name',
this.name); formData.append('age',
this.age); formData.append('file',
this.file); let
config = { headers:
{ 'Content-Type':
'multipart/form-data' } } this.$http.post('/upload',
formData, config).then(function (res) { if
(res.status === 2000) { /*這裏做處理*/ } }) } } }) } </ script > </ body > </ html > |