Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic DOM elements add/remove with Vue

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

like image 654
lewis4u Avatar asked Feb 28 '17 11:02

lewis4u


Video Answer


1 Answers

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.

like image 133
Belmin Bedak Avatar answered Sep 21 '22 09:09

Belmin Bedak