Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and removing divs dynamically in Vue JS component

Tags:

vue.js

vuejs2

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

})
like image 699
The_Ice_Man_cometh Avatar asked Oct 17 '25 19:10

The_Ice_Man_cometh


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

})
like image 98
Shizzen83 Avatar answered Oct 20 '25 14:10

Shizzen83



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!