Difficulty removing item from inverted list in Vue

1

I'm picking up time to use list in Vue. An inverted list for a computed display is displayed on the screen. I need to show it reversed so when you add an item it appears at the top. However, the way I did Vue is lost in removing the correct item from the list.

See my code: link

I made a button to add, which works correctly. In the "remove" I use the index of the item in the list to do a splice (), except that Vue uses this index in the inverted list, I imagined that it would use in the original list and then it would invert.     

asked by anonymous 29.11.2017 / 20:37

2 answers

1

You need to use the rolled index in the argument of this function as well:

reverse.length - 1 - index

Another way would be to pass id and then do

this.list = this.list.filter(obj => obj.id !== id)

or pass the item itself:

this.list = this.list.filter(obj => obj !== item)

Example with reverted index:

new Vue({
  el: '#box',
  data: {
    list: [{
        id: 1,
        name: 'item 1'
      },
      {
        id: 2,
        name: 'item 2'
      },
      {
        id: 3,
        name: 'item 3'
      }
    ]
  },
  methods: {
    add: function() {
      this.list.push({
        id: 100,
        name: 'novo item'
      })
    },
    del: function(index) {
      alert(index)
      this.list.splice(index, 1)
    }
  },
  computed: {
    reverse: function() {
      return this.list.slice().reverse()
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script><divid="box">
  <button @click="add">button</button>
  <ul>
    <li v-for="(item, index) in reverse">
      {{ item.name }} - <span class="del" @click="del(reverse.length - 1 - index)">remover</span>
    </li>
  </ul>
</div>
    
29.11.2017 / 20:51
2

Hello

The changes I would make in the code would be adding property key in html and using own item as reference for removal:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="box">
    <button @click="add">button</button>
    <ul>
      <li v-for="(item, index) in reverse" :key="item.id">
        {{ item.name }} - <span class="del" @click="del(item)">remover</span>
      </li>
    </ul>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

</body>
</html>

And in JS:

new Vue({
  el: '#box',
  data: {
    list: [
      {id: 1, name: 'item 1'},
      {id: 2, name: 'item 2'},
      {id: 3, name: 'item 3'}
    ]
  },
  methods: {
    add: function(){
      this.list.push({id: 100, name: 'novo item'})
    },
    del: function(item){
      alert(item.id)
      this.list.splice(this.list.indexOf(item), 1)
    }
  },
  computed: {
    reverse: function(){
      return this.list.slice().reverse()
    }
  }
})
    
29.11.2017 / 20:48