Vue中提交表单数据

来源:互联网 发布:python explode 编辑:程序博客网 时间:2024/05/17 23:27



这种方式可以提交,那么问题来了,表单提交以后如果需要获取服务器的响应呢,如果需要在响应成功后跳转页面呢,这种方式显得不好处理.

切回正题,在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>
  <metacharset="UTF-8">
  <metaname="viewport"content="width=device-width, initial-scale=1">
  <scriptsrc="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
  <scriptsrc="https://cdn.bootcss.com/axios/0.16.2/axios.js"></script>
</head>
 
<body>
  <form>
    <inputtype="text"value=""v-model="name"placeholder="请输入用户名">
    <inputtype="text"value=""v-model="age"placeholder="请输入年龄">
    <inputtype="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>
原创粉丝点击