0

Context: I'm making a simple todo app, where you can add & delete items.

Problem: When I click the "Delete" button on a specific item, this happens: it always deletes the last item in the list, instead of the clicked item.

Implementation details: I have a parent & child component. The child component is dinamically rendered with the help of v-for loop, when array gets populated. When button "Delete" is clicked, the child component emits a delete event to parent component. The parent component handles the delete functionality with the "detach()" method.

Code example https://codesandbox.io/s/polished-pine-nnbfo

I'm using splice() method in order to delete the specific component from array and though I'm providing the corect index of component that triggered the delete event, it always deletes the last component from array and I don't know why. Can someone point out the obvious, please ?

1 Answer 1

2

You are using too many arrays when you only need 1 array - the array with ToDo items.

<template>
  <div id="app">
    <label>
      First Name:
      <input type="text" name="firstName" v-model="firstName">
    </label>
    <label>
      Last Name:
      <input type="text" name="lastName" v-model="lastName">
    </label>
    <label>
      Email:
      <input type="email" name="email" v-model="email">
    </label>
    <button class="btn" @click="add">Send</button>

    <Todo
      v-for="(item,idx) in todoItems"
      :key="idx"
      :id="item.id"
      :first-name="item.firstName"
      :last-name="item.lastName"
      :email="item.email"
      @btnClick="detach(idx)"
    />
  </div>
</template>

<script>
import Todo from "./components/todo";

export default 
{
  name: "App",
  components: 
  {
    Todo
  },

  data() 
  {
    return {
      id: 0,
      firstName: '',
      lastName: '',
      email: '',
      todoItems: [],
    };
  },

  methods: {
    add() {
      this.todoItems.push({
        firstName: this.firstName,
        lastName: this.lastName,
        email: this.email,
        id: ++this.id,
      });
      this.firstName = '';
      this.lastName = '';
      this.email = '';
    },

    /** the delete function **/
    detach(index) 
    {
      this.todoItems.splice(index, 1);
    }
  }
};
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.