Search code examples
javascriptvue.jsaxiossplice

List items are removed from bottom to top but not from top to bottom


I made a list of items which are taken on the link. Near each element there is a button to delete when clicked on which the element should be removed from the site and api. The fact is that when I click on the delete button, everything is normal from the api, and from the site, if you delete the elements from the bottom up, it is normal, and if from top to bottom, it does not work correctly. I understand that the matter is in the splice parameters, but I do not know how to fix it.

Screenshot of list

<template>
  <div id="app">
    <ul>
      <li v-for="(post, id) of posts">
        <p>{{ post.title }}</p>
        <p>{{ post.body }}</p>
        <button  @click="deleteData(post.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'app',
  data () {
    return{
      posts: [],
    }
  },

    created(){
      axios.get('http://jsonplaceholder.typicode.com/posts').then(response => {
        this.posts = response.data
      })
    },
    methods: {
        deleteData(id) {
          axios.delete('http://jsonplaceholder.typicode.com/posts/' + id)
                    .then(response => {
                      console.log('delete')
                        this.posts.splice(id-1, 1)
                      })
                    .catch(function(error) {
                        console.log(error)
                    })
                  },
                }
              }
</script>

Solution

  • This id here is actually the index, not really the post.id, whereas splice() takes a start index, see the signature here:

    <li v-for="(post, id) of posts">
    <!----------------^^--- This is essentially posts[index] -->
    

    So try doing the following instead:

    <template>
      <div id="app">
        <ul>
          <li v-for="(post, index) of posts">
            <p>{{ post.title }}</p>
            <p>{{ post.body }}</p>
            <button @click="deleteData(index, post.id)">Delete</button>
          </li>
        </ul>
      </div>
    </template>
    
    methods: {
      deleteData(index, id) {
        axios
          .delete('http://jsonplaceholder.typicode.com/posts/' + id)
          .then(response => {
            this.posts.splice(index, 1);
          })
          .catch(function (error) {
            console.log(error)
          })
      },
    }