Vue JS always removing the first item

Asked

Viewed 117 times

2

Regardless of which line I try to delete, it always deletes the first:

Returns the following error: Property or method "$index" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

    <div class="container">
    <div id="table">
    <table class="table">
      <thead>
        <tr>
          <th>Clubes</th>
          <th>Socios</th>
          <th style="width: 36px;"></th>
        </tr>
      </thead>
      <tbody id="tbody">
        <tr v-for="item in list">
          <td>{{item.clube}}</td>
          <td>{{item.socio}}</td>
          <td>
              <a style="cursor: pointer;" v-on:click="removeLine($index)"><i class="glyphicon glyphicon-remove"></i></a>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
<script type="text/javascript">
    new Vue({
        el: '#table',

        data: {
            list: [{clube: 'Flamengo', socio: 'carl'}, {clube: 'Santos', socio: 'mark'}]
        },

        methods: {
            removeLine(index){
                this.list.splice(index, 1);
            }
        }
    });
</script>

1 answer

3


follows a complete example. the only difference, is that I am declaring the Dice within the v-for.

var app = new Vue({
  el: '#itens',
  data: {
    itens: [
      { clube: "Clube 01", socio: "Socio 01" },
      { clube: "Clube 02", socio: "Socio 02" },
      { clube: "Clube 03", socio: "Socio 03" },
      { clube: "Clube 04", socio: "Socio 04" },
      { clube: "Clube 05", socio: "Socio 05" },
      { clube: "Clube 06", socio: "Socio 06" }
    ]
  },
  methods: {
    remove: function (indice) {
      this.itens.splice(indice, 1);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<table id="itens">
  <thead>
    <tr>
      <th>Clube</th>
      <th>Socio</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, indice) in itens">
      <td v-html="item.clube"></td>
      <td v-html="item.socio"></td>
      <td>
        <button v-on:click="remove(indice)">Remover</button>
      </td>
    </tr>
  </tbody>
</table>

P.S.: $index is the syntax of Vue 1, in 2 you must declare as in the example above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.