splice(index,1)不删除元素

时间:2017-08-07 15:18:31

标签: html vuejs2

我正在Vue.js中编写一个小程序,但我遇到了错误。

我希望X按钮删除列表中的每个项目。我使用了splice(index,1),但该项目未被移除。我错过了什么?

我的HTML:

<div id="app" class="container">
  <div class="row">
    <div class="col-md-4">
      <h1>Add Student</h1>  
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" id="name" v-model="newStudent.name" class = "form-control" placeholder="Student Name">
        </div>  
        <div class="form-group">
          <label for="address">Address</label>
          <input type="text" id="address" v-model="newStudent.address" class = "form-control" placeholder="Address">
        </div>  
        <button class="btn btn-success" v-on:click = "addStudent">Add</button>  
      </div>
      <div class="col-md-8">
        <h1>All Students</h1>
        <table class="table table-striped">
          <thead>
            <tr>
              <td>Name</td>
              <td>Address</td>
              <td>Action</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for = "student in students">
              <td>{{student.name}}</td>
              <td>{{student.address}}</td>
              <td><button type="button" class="btn btn-danger" v-on:click="deleteStudent($index)">X</button></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div> <!--End of Row-->
    <br>
    <br>

    <div class="row">
      <div class="col-md-12">
        <pre>{{ $data |  json }}</pre>
      </div>
    </div>
  </div>

我的JS:

<script>
  new Vue({
    el: "#app",
    data: {
      newStudent: {name: "", address: ""},
      students: []
    },
    methods: {
      addStudent: function(){
        var name = this.newStudent.name.trim();
        var address = this.newStudent.address.trim();
        if(name && address){
          this.students.push({name: name, address: address});
          this.newStudent = {name: "", address: ""};
          $("#name").focus();
        }
      },
      deleteStudent: function(index){
        this.students.splice(index,1)
      }
    }
  });
</script>

1 个答案:

答案 0 :(得分:0)

$index变量was removed in Vue 2。所以,你没有正确传递索引。

index中指定v-for变量,然后将其传递给deleteStudent方法:

<tr v-for="student, index in students">
  <td>{{student.name}}</td>
  <td>{{student.address}}</td>
  <td>
    <button 
      type="button" 
      class="btn btn-danger" 
      v-on:click="deleteStudent(index)"
    >X</button>
  </td>
</tr>

This is covered in the documentation on list rendering in Vue.