Adding and removing divs dynamically in Vue JS component

Viewed 3889

I am new to VueJS and now I face a problem I just can't figure out. I want to add and remove elements dynamically by clicking buttons. How do I get this to work, so I can remove a specific div and not always the last one I added. I played around with this a lot and now I even get an error [Vue warn]: You may have an infinite update loop in a component render function. I likely shouldn't set div=index and instead work with div.id etc. Hope someone can help me out with this. Thanks.

https://jsbin.com/zuquwej/edit?html,js,output

  <div id="app">

    <div
      v-for="(div, index) in divs"
      :key="div.id"
      :div="div=index"
    >
      <div class="row">
        <div class="col-12">Div {{div}}</div>
      </div>

      <button
        class="btn btn-danger"
        @click="deleteRow(index)"
      >Delete</button>

    </div>

    <button
      class="btn btn-success"
      @click="addRow"
    >Add row</button>

  </div>
const app = new Vue({

  el: '#app',

 data() {
    return {
      div: 0,
      divs: []
    };
  },

  methods: {
    addRow() {
      this.divs.push({
        div: this.div
      });
      console.log(this.divs);
    },
    deleteRow(index) {
      this.divs.splice(index, 1);
    }
  }

})
1 Answers

You should store an index each object you generate and store into component's divs property. By the way, unlike array index, it won't change if you splice an element from this array. Here is a working example:

<div
      v-for="div in divs"
      :key="div.id"
    >
      <div class="row">
        <div class="col-12">Div {{ div.name }}</div>
      </div>

      <button
        class="btn btn-danger"
        @click="deleteRow(div.id)"
      >Delete</button>

    </div>
const app = new Vue({ 
  el: '#app',

  data() {
    return {
      index: 0,
      divs: []
    };
  },

  methods: {
    addRow() {
      this.divs.push({
        id: this.index,
        name: 'div' + this.index,
      });
      this.index++;
    },
    deleteRow(index) {
      this.divs.splice(index, 1);
    }
  }

})
Related