[Vuejs]-Delete an element from array nuxtjs

0👍

Observations :

  • As deletePost() method is responsible to make an API call to delete the selected record from the backend. Then, Why you are deleting that again at client side ? API should response with the filtered data and you can directly assign that in this.posts.
  • this.posts.data is an array of objects and id is a number. Hence, this.posts.data.indexOf(id) will not work.

Let me explain with a demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      posts: [{
        id: 1,
        title: 'Title 1',
        excerpt: 'Excerpt 1',
        updated_at: 'Updated 1'
      }, {
        id: 2,
        title: 'Title 2',
        excerpt: 'Excerpt 2',
        updated_at: 'Updated 2'
      }, {
        id: 3,
        title: 'Title 3',
        excerpt: 'Excerpt 3',
        updated_at: 'Updated 3'
      }, {
        id: 4,
        title: 'Title 4',
        excerpt: 'Excerpt 4',
        updated_at: 'Updated 4'
      }]
    }
  },
  methods: {
    deletePost(id) {
      // make an API call and bind the response directly in this.posts
      this.posts.forEach((obj) => {
        if (id === obj.id) {
          this.posts.splice(this.posts.indexOf(obj), 1);
        }
      })
    }
  }
})
.link {
  color: blue;
  cursor: pointer;
  text-decoration: underline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>
<div id="app">
  <table>
    <tr v-for="post in posts" :key="post.id">
      <td>{{ post.title}}</td>
      <td>{{ post.excerpt}}</td>
      <td>{{ post.updated_at }}</td>
      <td class="link" @click="deletePost(post.id)">Delete</td>
    </tr>
  </table>
</div>

Leave a comment