Vue中提交表單數據



這種方式可以提交,那麼問題來了,表單提交以後如果需要獲取服務器的響應呢,如果需要在響應成功後跳轉頁面呢,這種方式顯得不好處理.

切回正題,在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">
  <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
</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>
發佈了12 篇原創文章 · 獲贊 5 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章