Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  7] [ 4]  / answers: 1 / hits: 58625  / 7 Years ago, tue, february 28, 2017, 12:00:00

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


More From » html

 Answers
105

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 our inputs array (with predefined schema), and give it unique index.



Here is the example: http://jsbin.com/zusokiy/edit?html,js,output



Template:



  <div id=app>

<ul>
<li v-for=(input, index) in inputs>
<input type=text v-model=input.one> - {{ input.one }}
<input type=text v-model=input.two> - {{ input.two }}
<button @click=deleteRow(index)>Delete</button>
</li>
</ul>

<button @click=addRow>Add row</button>

</div>


JS:



const app = new Vue({

el: '#app',

data: {
inputs: []
},

methods: {
addRow() {
this.inputs.push({
one: '',
two: ''
})
},
deleteRow(index) {
this.inputs.splice(index,1)
}
}

})


Better option would be maybe break it into components, but this is so far, so good.


[#58743] Saturday, February 25, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycoborionc

Total Points: 220
Total Questions: 106
Total Answers: 120

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;