在VueJS中提交表单后,将更新的数据填充到表中

时间:2018-07-19 14:25:29

标签: javascript post vue.js

我有一个端点可以使用POST请求提交数据,

http://localhost:3000/entry

键是fname,lname,age

我可以向给定的端点发出POST请求,它将创建一个条目。它成功提交了数据。但是,无论何时提交表单,它都将重定向到端点(即http://localhost:3000/entry)。我不想重定向URL。我正在使用VueJS。

我还有一个终点,

http://localhost:3000/entries(GET),它以JSON返回所有现有条目。例子

[
    {
        "_id": "5b48a137c3b2a3454b853a3c",
        "fname": "John",
        "lname": "Jose",
        "age": "28",
        "__v": 0
    },
    {
        "_id": "5b506cc7d9105012f59c87e6",
        "fname": "Alex",
        "lname": "Cruz",
        "age": "27",
        "__v": 0
    }
]

我不想重定向到端点URL,而是想在提交表单时通过调用API http://localhost:3000/entries来填充HTML表中的更新数据。

index.html:-

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>



<div id="app">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 

    <form class="row" id="app" @submit="checkForm" action="http://localhost:3000/entry" method="post">
      <div class="col-sm-12">
        <div class="form-group">
          <label for="url">First Name</label>
          <input type="text" class="form-control" value="" v-model="fname" name="fname" />
        </div>
        <div class="form-group">
          <label for="team">Last Name</label>
          <input type="text" class="form-control" value="" v-model="fname" name="fname" />
        </div>
        <div class="form-group">
          <label for="environment">Age</label>
          <input type="text" class="form-control" value="" v-model="age" name="age" />
        </div>
      </div>
      <div class="col-sm-12">
        <input href="#" class="btn btn-success" type="submit" value="Submit">
      </div>
    </form> 

    <div>&nbsp;</div>

    <div class="row" v-if="debug">
      <div class="col-sm-12">
        <pre>{{ $data | json }}</pre>
      </div>
    </div>

    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr>
          <td>{{fname}}</td>
          <td>{{lname}}</td>
          <td>{{age}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>

script.js:-

const app = new Vue({
  el:'#app',
  data:{
    errors:[],
    fname:null,
    lname:null,
    age:null
  },
  methods:{
    checkForm:function(e) {
      if(this.fname) return true;
      this.errors = [];
      if(!this.fname) this.errors.push("First name required.");
      e.preventDefault();
    }
  },

})

更新表:-

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.16/vue-resource.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>



<div id="app">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 


    <form class="row" @submit.prevent="checkForm">
      <div class="col-sm-12">
        <div class="form-group">
          <label for="url">First Name</label>
          <input type="text" class="form-control" value="" v-model="fname" name="fname" />
        </div>
        <div class="form-group">
          <label for="team">Last Name</label>
          <input type="text" class="form-control" value="" v-model="lname" name="lname" />
        </div>
        <div class="form-group">
          <label for="environment">Age</label>
          <input type="text" class="form-control" value="" v-model="age" name="age" />
        </div>
      </div>
      <div class="col-sm-12">
        <input href="#" class="btn btn-success" type="submit" value="Submit" :disabled="isSaving">
        <span v-show='isSaving'>Saving...</span>
      </div>
    </form> 

    <div>&nbsp;</div>



    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr v-for="item in objects" :key="item._id">
          <!-- item.fname -->
          <td>{{item.fname}}</td>
          <!-- item.lname -->
          <td>{{item.lname}}</td>
          <!-- item.age -->
          <td>{{item.age}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>

2 个答案:

答案 0 :(得分:0)

如果您在fname-input中输入了任何内容,则checkForm方法将在e.preventDefault()之前返回。将e.preventDefault()移动到方法的顶部,这将阻止导航表单。

此外,您的姓氏输入也将fname作为v模型。

要填充表格,我将使用以下内容:

index.html

<table style="width:100%">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
    </tr>
    <tr v-for="(row, index) in table" :key="index">
        <td>{{row.fname}}</td>
        <td>{{row.lname}}</td>
        <td>{{row.age}}</td>
    </tr>
</table>

script.js

data: {
    return {
        ...
        table: []
    }
},
mounted() {
    this.populateTable()
},
methods: {
    checkForm(e) {
        e.preventDefault();
        if (this.fname) {
            table.push({ fname: this.fname, lname: this.lname, age: this.age })
            return true;
        }
        this.errors = [];
        if (!this.fname) this.errors.push("First name required.");
        return false;
    },
    populateTable() {
        /* GET-request, put into this.table */
    }
}

答案 1 :(得分:0)

您需要使用ajax请求而不是表单操作将数据传递到服务器:

  1. 在模板form中应这样打开(没有操作和方法):

    <form class="row" @submit.prevent="checkForm">
    
  2. 使用ajax将数据发送到服务器(我看到您使用 vue-resource ):

    checkForm:function(e) {
        this.errors = [];
        if(!this.fname) this.errors.push("First name required.");
        if (this.errors.length) {
           return;
        }
        var data = {
            fname: this.fname,
            lname: this.lname,
            age: this.age
        }
        this.$http.post('http://localhost:3000/entry', data, { emulateJSON: true })
        .then(function(){
            console.log('Saved!');
         });
    }
    
  3. 因此表中的数据会自动更新。

更新

您现在还需要对象数组来正确呈现表。 我准备了示例,但是我将URL更改为jsonplaceholder来表明它可行。 保存表单应用程序后,从服务器获取所有对象(但在我的示例中您将看不到新创建的对象,因为我使用的公共API不允许更改整个集合,只允许发出请求,当您添加正确的自己的URL时它将起作用)。另外,您需要将表中的输出字段更改为更正的字段-我添加了注释。

const app = new Vue({
  el:'#app',
  data:{
    errors:[],
    fname:null,
    lname:null,
    age:null,
    isSaving: false,
    objects: []
  },
  created() {
      this.getAll();
  },
  methods:{
    checkForm:function(e) {
      this.errors = [];
      if(!this.fname) this.errors.push("First name required.");
      if (this.errors.length) {
         return;
      }
      this.isSaving = true;
      var data = {
          fname: this.fname,
          lname: this.lname,
          age: this.age
      }
      // http://localhost:3000/entry
      this.$http.post('https://jsonplaceholder.typicode.com/users', data, { emulateJSON: true })
      .then((resp) => {
          console.log(resp);
          return this.getAll();
       })
       .then(() => {
          this.isSaving = false;
          this.fname = null;
          this.lname = null;
          this.age = null;
       })
    },
    
    getAll() {
       // http://localhost:3000/entries
       this.$http.get('https://jsonplaceholder.typicode.com/users')
       .then((data) => {
           console.log(data);
           this.objects = data.body;
       })
    }
  },

})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.5.1/vue-resource.min.js"></script>
<div id="app">
  <div class="container">

    <div class="row">
      <div class="col-sm-12">
        <h3>
          Dashboard
        </h3>
      </div>
    </div> 

    <form class="row" @submit.prevent="checkForm">
      <div class="col-sm-12">
        <div class="form-group">
          <label for="url">First Name</label>
          <input type="text" class="form-control" value="" v-model="fname" name="fname" />
        </div>
        <div class="form-group">
          <label for="team">Last Name</label>
          <input type="text" class="form-control" value="" v-model="lname" name="lname" />
        </div>
        <div class="form-group">
          <label for="environment">Age</label>
          <input type="text" class="form-control" value="" v-model="age" name="age" />
        </div>
      </div>
      <div class="col-sm-12">
        <input href="#" class="btn btn-success" type="submit" value="Submit" :disabled="isSaving">
        <span v-show='isSaving'>Saving...</span>
      </div>
    </form> 

    <div>&nbsp;</div>

    <!--<div class="row" v-if="debug">
      <div class="col-sm-12">
        <pre>{{ $data | json }}</pre>
      </div>
    </div> -->

    <!-- Table Start -->

    <div class="row">
      <table style="width:100%">
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Age</th>
        </tr>
        <tr v-for="item in objects" :key="item._id">
          <!-- item.fname -->
          <td>{{item.name}}</td>
          <!-- item.lname -->
          <td>{{item.username}}</td>
          <!-- item.age -->
          <td>{{item.email}}</td>
        </tr>
      </table>
    </div>
    <!-- Table END -->

  </div>
</div>