remove function erases all the data in Vue

My goal is to delete only the item that has been clicked on.

todoList Component:

template :

<ul class="list-group">
                  <todo v-for="(todo,i) in todo" :key="i" :todoString="todo.todoString" :completed="todo.completed"
                  @on-delete="del(todo)" />
              </ul>

script :

 data() {
    return {
      todo: [
        { todoString: "make videos Angular", completed: true },
        { todoString: "make videos React", completed: false },
        { todoString: "make videos Vue", completed: true },
        { todoString: "make videos Javascript", completed: false },
      ],
    };
  },
 
 del(deltodo) {
          this.todo = this.todo.filter(todos => {
            todos.todoString !== deltodo.todoString;
           console.log(this.todo.length)
          });
          console.log(this.todo.length)
        },

TodoComponent :

template:

<li class="d-flex align-items-center list-group-item">
    <button class="btn border-0 text-left flex-grow-1">{{todoString}}</button>
    <form action="" class="flex-grow-1">
        <input type="text" class="form-control">
    </form>

    <button class="btn btn-outline-primary">Edit</button>
    <button  key="" @click="$emit('on-delete')" class="btn btn-outline-danger">delete</button>

</li>

script :

props:{
    todoString:String,
    completed:Boolean
},

The issue arises when I delete one item, as it ends up deleting all the items.

Answer №1

To improve efficiency, it is recommended to pass the index instead of the entire object when using the del method:

@on-delete="del(i)"

The del method can then be implemented with the splice function:

del(i) {
  // remove 1 element at index i
  this.todo.splice(i, 1);
}

If you prefer to use filter, make sure to return from the callback function:

this.todo = this.todo.filter(todos => {
  return todos.todoString !== deltodo.todoString
});

Answer №2

When using v-for, it is important to avoid naming the single element the same as your array to prevent any potential issues.

<ul class="list-group">
                  <todo v-for="(item,index) in todos" :key="index" 
                    :todoString="item.todoString" :completed="item.completed"
                    @on-delete="deleteItem(item)" />
              </ul>

Your filter function also needs to have a return statement for it to work correctly. Update it like this:

 deleteItem(itemToDelete) {
          this.todos = this.todos.filter(entry => {
            console.log(this.todos.length);
            return entry.todoString !== itemToDelete.todoString;
          });
          console.log(this.todos.length)
        },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Material UI Autocomplete for Categorical Selections in a ReactJS Application

Using MUI Autocomplete and Formik, I'm looking to organize items into categories. If an item doesn't have any sub_accounts, then it should not display a header label. Check out the example here: https://mui.com/material-ui/react-autocomplete/#gro ...

What is the process for retrieving the response from a PayPal pre-approval?

I am currently utilizing the "paypal-adaptive" package to implement PayPal preapproval. You can find more information about it here: https://www.npmjs.com/package/paypal-adaptive. Here is a snippet of my code: export const paypalPreapproval = async () =& ...

Open a new tab in Chrome and take a screenshot of the freshly created tab

I am encountering an issue with capturing a newly created tab in Chrome. When I use chrome.tabs.create to create a new tab and pass the tabid to my callback function for capturing, it does not work as expected. function createNewTab(url) { chrome.tabs.c ...

Click to delete the <p> element

For the past few days, I've been struggling with this issue and have tried various approaches to solve it. However, I can't seem to remove the element for some reason. Can anyone offer some insight? My objective is to add the inputted markup on ...

GraphQL Error (Status Code: 429) - Next.js Development issue

If you're facing a GraphQL Error (Code: 429) while working on a nextjs project, here's a handy solution. Here's what happened: I created a headless CMS using Hygraph and NextJS 13 for a blog project. I also utilized the npm package graphql ...

AngularJS: Establishing effective communication channels among directives

I am currently developing a custom directive for an audio player that supports mp3 files. The challenge I'm facing is how to handle multiple instances of the player on a single page. My goal is to ensure that when one player is active, starting anothe ...

What is the best way to showcase a route parameter in the context of Vue.js and Firebase integration

I am currently working on a blog project that offers free sewing patterns as content. My approach involves using route parameters to fetch each blog individually. However, I have encountered an issue where the blog's data is not being retrieved from f ...

Is there a way to create animated CSS box-shadow depth using jQuery or CSS3 transitions?

This code snippet applies delays but doesn't seem to update the style changes until the loop completes: for (i=20;i>=0;i--) { var boxShadow = i+"px "+i+"px "+i+"px #888"; $('article').css("box-shadow", boxShadow); ...

The returned data from a Apollo Client useMutation call is consistently undefined

Currently, I have a code snippet that executes a mutation to update a post to "published." The mutation functions correctly and updates the data as intended. However, I am facing an issue where the data property remains undefined in the useMutation hook. S ...

Display the dist file (from Vue.js) within Django

After successfully rendering the Vue.js build (index.html) in Django, a problem arises when attempting to add any routes to the URL. In such cases, it results in a "page not found" error from Vue. Rendering without routes works perfectly fine: url(r' ...

Mongoose: The aggregate method does not filter properly when using Model.field_1.field_2

Explaining a custom function: const getNotificationsForLounge = async (lounge_id) => { try { const notifications = await Notification.aggregate([ { $match: { "lounge_join_request.lounge": lounge_id, loun ...

How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+". When the user hovers over it, I use element.append(' Add a New Number'); to add the text "Add a New Number" next to the + sign in the label. Upon clicking the button, a new number is added and ...

What is the best way to make a JavaScript cookie remember the state of a DIV?

Seeking assistance with a test site here that is currently in development. I am attempting to make the notification at the top remain hidden once the close button is clicked. Below is my current script: <style type="text/css"> <!-- .hide { displ ...

Maintain checkbox selection even after leaving the page

I am looking for a way to maintain the state of a checkbox even after navigating away from the page in an AngularJS and bootstrap environment. Currently, I find that my bound variable gets reset to false every time I reload the page when the controller run ...

Chai can't verify the HTML component

During my testing of an Angular project, I initially used Jasmine to check if a specific attribute of an HTML element exists. The following code snippet worked successfully for me: expect(element(by.css("*[id='ref_button']")).getAttribute(&ap ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Execute a JavaScript function when a form is submitted

Seeking to reacquaint myself with Javascript, encountering difficulties with this fundamental issue. https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/ var name = document.getElementById("name"); function validate() { alert("Your name is " +name); } < ...

Triggering the body onunload event

I am currently developing a HTA that needs to make final modifications on the onunload event. However, I am facing an issue as the event does not appear to be triggered. Can someone confirm if this event is still supported? Is there an equivalent event in ...

SQL - Retrieve information for a specified time frame using a predetermined value

I am looking to retrieve data from a table, extract the information using JavaScript, and visualize it on a graph where the x-axis represents dates and the y-axis represents numbers. The DATA table is structured as follows (please note that attempts to fo ...

Deciphering the hidden power of anonymous functions within Express.js

Recently, I started learning about express and am grappling with understanding callbacks in RESTful actions. In the following PUT request code snippet, I am puzzled by the specific line that is highlighted below. Why is response.pageInfo.book being assigne ...