2017-08-07 100 views
0

我在Vue.js中寫了一個小程序,但是我遇到了一個錯誤。splice(index,1)不能刪除元素

我想要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> 

回答

0

$index變量was removed in Vue 2。所以,你沒有正確傳遞索引。

指定在v-forindex變量並傳遞到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.

+0

謝謝。有用。教程可能是舊的。 –