What causes the index-of method to malfunction in Vue.js?

I created a Vue.js custom component with a list that includes a delete button. However, whenever I click on the button to delete a row, it always deletes the last row instead of the intended one. Why is this happening? To see my code, click on the provided link: https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview

 methods: {
        deleteTodo:function (item) {
            console.log(item)
            var index = this.items.indexOf(item);
            this.items.splice(index, 1);
        }
    }

Full Code:

var MyComponent = Vue.extend({
    template:'#todo-template',
    props:['items'],
    computed: {
        upperCase: function () {
            return this.items.map(function (item) {
                return {name: item.name.toUpperCase(),complete:item.complete};
            })
        }
    },
    methods: {
        deleteTodo:function (item) {
            console.log(item)
            var index = this.items.indexOf(item);
            this.items.splice(index, 1);
        }
    }
})
Vue.component('my-component', MyComponent)

var app = new Vue({
    el: '#App',
    data: {
        message: '',
        items: [{
            name: "test1",
            complete:true
        }, {
            name: "test2",
            complete:true
        }, {
            name: "test3",
            complete:true
        }]
    },
    methods: {
        addTodo: function () {
           this.items.push({
               name:this.message,
               complete:true
           });
           this.message ='';
        },
    },
    computed: {
        totalCount:function () {
            return this.items.length;
        }
    }
});

Answer №1

To improve efficiency, consider passing the index of the item instead of the entire object.

Modify the for loop to:


<li v-for="(item, index) in upperCase" v-bind:class="{'completed': item.complete}">
    {{item.name}}
    <button @click="deleteTodo(index)">X</button>
    <button @click="deleteTodo(index)">Toggle</button>
</li>

Adjust the delete function to:


deleteTodo:function (itemIndex) {
    this.items.splice(itemIndex, 1);
}

See updated code here: Link

Answer №2

Make sure to handle cases where indexOf may not return a valid index.

    deleteTodo:function (item) {
        console.log(item)
        var index = this.items.indexOf(item);
        this.items.splice(index, 1);
    }

If the index returned is -1, it means that the item could not be found in the list. It's possible that this.items is not what you expect it to be.

To address this issue, consider adding some defensive code:

    deleteTodo:function (item) {
        console.log(item)
        var index = this.items.indexOf(item);
        if (index === -1)
          console.error("Could not find item "+item+" in list: ",this.items);
        else
          this.items.splice(index, 1);
    }

This modification will provide insight into the contents of this.items via console output.

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

What could be causing the parsing issue on the page for Node.js?

When attempting to access the given page with invalid credentials: In a browser, I receive well-formatted JSON: { "error": { "code": "request_token_invalid", "message": "The access token isn't valid." } } However, trying the equi ...

Vue-Superagent.post does not exist as a valid function in this context

While attempting to upload a file using vue-superagent, I encountered an issue with my code. Previously functional, I am now receiving the following error message: vue_superagent__WEBPACK_IMPORTED_MODULE_5___default.a.post is not a function //@ts-ig ...

The function _vm.$refs.menu.open is not defined

Utilizing vue-context to customize the default context menu, I encounter an error when trying to interact with it from a component. Below is my code snippet: <!-- Main --> <p @contextmenu.prevent="$refs.menu.open">test</p> <C ...

Tips for designing a versatile component to handle numerous buttons triggering form pop-ups

library used: mui 5.4.1 To implement a TableCell with an IconButton that triggers the opening of a Form, follow this code snippet. const items = [ { id: "001", name: "A", price: 2000 }, { id: "002", name: &q ...

Modify a particular entry that is being looped through in PHP

Currently, I have coded the following: <div class="row"> <div class="col-lg-12"> <table id="usertable" class="table table-bordered table-hover text-center"> <thead> <th class="col-lg-1 text-center">User ID</th> ...

What is the best method for displaying 3 items in each row from a mapped response in ReactJS using materialize css grids or react bootstrap grids?

I have been attempting to display three or four response items in a mapped out response on the same row, but I haven't had much success. While I have researched similar questions on Stack Overflow, I couldn't quite figure out how to apply those s ...

Guide to making a tooltip using vue.js

Currently, I am developing a Vue2 application that requires a tooltip with interactive buttons to only appear when text in a textarea is selected. I have been searching for a library similar to the one found at , but specifically for Vue2. Despite an ext ...

Tips on resolving the issue of an Axios post request not appearing in a get request in React

When using axios to make a post request in this code, a new username is posted, but there is an issue with retrieving the posted name from the API. How can I fix this problem to view my posted request? const App = () => { const [data, setData] = u ...

issue with a xmlhttp request

A JavaScript function using xmlhttp is shown below: var params = "a=" + encodeURIComponent(a) + "&b=" + encodeURIComponent(b) + "&c=" + encodeURIComponent(c); var url = "noob.php"; xmlHttp2.open("POST", url, true); xmlHtt ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Fixing the department display list in React Hook: A step-by-step guide

{ roomDept.map((item, index) => ( <div key={index} className="flex flex-col pb-2 items-center"> <div className="flex pb-2 w-full"> <SelectPick ...

The azure-graph platform has detected a Request_BadRequest error due to an invalid domain name being included in the

I am attempting to use Node.js to retrieve the user object based on its ID. Below is the code I have written: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, ke ...

How can I accurately show the server time and timezone in JS/jQuery regardless of the user's location?

Apologies for bringing up another time and timezone question related to web development. Despite numerous resources available, I am still struggling to grasp the concept of converting time between PHP and JavaScript. Here is my scenario: I aim to retrieve ...

Expandable Grid with UI-GRID - Automatically expand a row when clicked on

I prefer not to utilize the default + icon for expanding the row. The row should expand when clicked anywhere on it. I attempted the following: HTML <div ui-grid="gridOptions" ui-grid-expandable class="grid"> Controller var app = angular.module( ...

Why doesn't my constructor promise to not replace data?

I need help figuring out where I'm going wrong with my code. I have a class that has a constructor and two methods. My goal is for the `find()` method to push data from a query into an array. However, I'm not sure why the array values seem to dis ...

VueJs Nuxt PWA displays incorrectly on iPhone

I recently encountered a strange problem with my VueJS Nuxt portfolio website (). It seems to be working perfectly on all devices except for iOS phones. When accessed on iOS devices, only a red spinner is shown and nothing else loads. What could be causing ...

Is it possible to transmit both HTML and PHP files using express.js?

Is it possible to serve HTML files for one page and PHP files for another with an express.js app? Here's a theoretical example: var express = require('express.js') var app = express() app.get('/php', function (req, res) { res.se ...

When you click on the Prev/Next arrow in the JS slider, the image suddenly

I've been struggling to find a solution for this issue. This is my first attempt at using JS as I am in the process of learning. It's very likely that I'm not fully grasping the answers from my searches - apologies for that. What I'm l ...

Utilizing a personalized service within an extended RouterOutlet component in Angular 2 for streamlined authentication

In my quest to establish authentication in Angular 2, I turned to an insightful article (as well as a previous inquiry on SO) where I learned how to create a custom extended RouterOutlet: export class LoggedInRouterOutlet extends RouterOutlet { public ...

Hovering over an option in Vue-Bootstrap b-select

I'm working with the Vue-Bootstrap framework and I need to update the CSS rule for the 'option' tag when it is being hovered over. Here is my code snippet: jsfiddle option:hover { background-color: red; } Can someone please explain why ...