Reputation: 135
I'm brand new to Vue and have been struggling with this all day. I am trying to build a table using Vue components that can allow users to add and remove rows.
The problem I'm having is the removeRow()
fuction is not removing the selected row, it's removing the last row off the table. Can anyone help me out?
Vue.component('newtemplate', {
template: `<div>
<div>
<button class="button btn-xs btn-success" @click="addRow">+</button>
</div>
<table>
<thead>
<tr>
<th class="col-lg-6 nopadding"><input type="text" value="Col 1" class="borderless nopadding col-lg-6"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 2" class="borderless nopadding col-lg-12"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 3" class="borderless nopadding col-lg-12"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 4" class="borderless nopadding col-lg-12"></th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :row="row">
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<button type="button" class="text-center button btn-xs btn-danger" v-on:click="removeRow(index)">-</button>
</td>
</tr>
</tbody>
</table>
</div>`,
data: function() {
return {
rows: [{row: ""}]
}
},
methods:{
addRow(){
this.rows.push({row: ''});
},
removeRow: function(index) {
this.rows.splice(index, 1);
}
}
});
UPDATE I made a fiddle https://jsfiddle.net/4d2uzx0r/
Upvotes: 4
Views: 23478
Reputation: 31352
Add a key
attribute to your row element
<tr v-for="(row, index) in rows" :key="index" :row="row">
//...
</tr>
Unique keys for elements rendered with v-for
loop helps vue's virtual dom to overcome rendering errors by identifying VNodes when diffing the new list of nodes against the old list.
See docs for more info about key
attribute
Upvotes: 1
Reputation: 43881
Vue is removing the appropriate item from rows
, but you don't have your inputs bound to anything, so Vue doesn't know about the values in the table row inputs, it only knows that it needs to render fewer rows. Vue takes shortcuts when it can and can only keep track of state that it knows about.
I've updated your fiddle to bind the first column to a row element (each row item is now an array). If you fill in values in the first column, you can see that it deletes the appropriate row.
<input type="text" class="form-control nopadding text-center" v-model="row[0]">
and
addRow() {
this.rows.push({
row: []
});
},
removeRow: function(index) {
console.log("Removing", index);
this.rows.splice(index, 1);
}
Upvotes: 1