I have started to learn Vue.js and i can't figure it out how would you do this in Vue.js like I did it with jQuery:
<!-- jQuery -->
<h2>jQuery</h2>
<table id="t1">
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
<tr id="r1">
<td><input name="item[]" type="text"/></td>
<td><input name="quantity[]" type="number"/></td>
<td><button class="deleteRow">X</button></td>
</tr>
</table>
<button id="addRow">Add Row</button>
.js
// jQuery
$(document).on('click', '#addRow', function(){
var row = parseInt($('#t1 tr:last-child').attr('id')) + 1;
alert(row);
$('#t1').append('<tr id="r'+row+'"><td><input name="item[]" type="text"/></td><td><input name="quantity[]" type="number"/></td><td><button class="deleteRow">X</button></td></tr>');
});
$(document).on('click', '.deleteRow', function(){
var row = parseInt($(this).closest('tr').attr('id'));
$('#r'+row).remove();
});
How to create a whole new element on a click with Vue and how to remove it?
Here is all loaded in JSFiddle
VueJS is data driven, so forget on direct DOM manipulations.
In example below, you will see that I've defined the
inputs
array - that's the place where would we store all rows - so it would be array of objects.In our template we're iterating through the
inputs
array and for each input we send index too - required for row deleting.addRow
is method push new object to ourinputs
array (with predefined schema), and give it unique index.Here is the example: http://jsbin.com/zusokiy/edit?html,js,output
Template:
JS:
Better option would be maybe break it into components, but this is so far, so good.