Add / Remove Dynamic DOM Elements Using Vue

I started learning Vue.js and I can’t figure out how you do it in Vue.js, how 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 completely new item when clicked with Vue and how to remove it?

Everything is uploaded to JSFiddle here.

+4
source share
1 answer

VueJS is data driven, so forget about the direct manipulation of the DOM.

In the example below, you will see that I defined an array inputs- the place where all the rows will be stored - so it will be an array of objects.

In our template, we repeat the array inputs, and for each input we also send an index - required to delete a row.

addRow - push inputs ( ) .

: http://jsbin.com/zusokiy/edit?html,js,output

:

  <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)
    }
  }

})

- , , , .

+7

Source: https://habr.com/ru/post/1671029/


All Articles