Removing a row by its id in VueJs using the splice method

After successfully deleting an item from the database, I am facing an issue where the item is not being removed from the list.

I understand that I should use the index to splice the item from the list. However, using the index means I cannot pass the itemID to the backend, creating a dilemma.

Challenge

  1. If I use the index, it sends the index number to the backend, which is incorrect.
  2. If I use the itemId, the item gets deleted from the database but remains in the list.

Code

HTML

<el-col :span="9" style="margin-top:15px;">
    <template v-for="itemm in item.children" >
        <div :key="itemm.id">
            <!-- child's -->
            <el-input :value="itemm.name" placeholder="Please input your variation value" class="input-with-select">
            <el-button slot="append" @click="removeSavedChild(itemm.id)" type="danger" icon="el-icon-delete"></el-button>
            </el-input>
        </div>
    </template>
</el-col>

Script

data() {
  return {
     savedVariations: [],
  }
},
methods: {
  removeSavedChild(id){
    axios.delete('/api/admin/variations/destroy/'+id).then((res) => {
        console.log(res.data.success);
        this.savedVariations.splice(id, 1);
    })
    .catch((err) => {
        console.log(err)
    });
  },
}

Any suggestions or solutions?

Answer №1

If you want to remove a saved child item, you can do so by using both the id and index. Here is an example:

removeSavedChild(id, index, items){
    axios.delete('/api/admin/variations/destroy/'+id).then((res) => {
        console.log(res.data.success);
        items.splice(index, 1);
    })
    .catch((err) => {
        console.log(err)
    });
  },

When triggering the click event, pass the parameters like this:

@click="removeSavedChild(itemm.id, index, item.children)"

Make sure to include the index in your for loop as well:

<template v-for="(itemm, index) in item.children" >

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

Java script pop-up notifications always show up

This Text Goes Above the Form <?php require_once "core-admin/init-admin.php"; if( !isset($_SESSION['admin_username']) ){ $_SESSION['msg'] = 'page cannot be opened'; header('Location:admin_login.php&ap ...

Why does my array become empty once it exits the useEffect scope?

const [allJobs, setAllJobs] = useState([]); useEffect(() => { axios.get('http://localhost:3002/api/jobs') .then(res => setAllJobs(res.data)); allJobs.map((job, i) => { if (job.language.toLowerCas ...

Exploring methods for testing an HTML page that utilizes jQuery for DOM manipulations

Recently, I was tasked with creating an HTML page that utilized jQuery DOM manipulations. For instance, upon clicking the submit button, a success or error message should be displayed. Testing these functionalities is something I'm familiar with in An ...

Using Vue.compile in Vue 3: A beginner's guide

Is there a way to utilize Vue.$compile for compiling functions in Vue 3 runtime? I have previously used this function in Vue 2, an example being: Vue.compile('<custom-component />'); ...

I am experiencing issues with my local MongoDB database not properly storing data when using Express and Mongoose

I am encountering an issue where my code is functioning correctly in the console but it is not saving data to the database. Every time I restart the server, the data gets reset. While I can read data from the database without any problem, the issue arise ...

What could be causing the npm server error in my Vue.js application?

After recently setting up Node.js and Vue.js, I decided to dive into my first project on Vue titled test. As part of the process, I attempted to configure the server using the command: npm run server However, I encountered the following error message: C ...

Are there any notifications triggered when a draggable element is taken out of a droppable zone?

Within a single droppable area, there is a collection of individual Field Names that can be dragged, and a table featuring X headers, each of which can be dropped into. Initially, these headers are empty. Is there a way to detect when an item is taken out ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

If the condition has a class name of condition, then display

Having performance issues due to slow data rendering with each tab using a partial view. The code snippet for each tab is as follows: <div class="tab-content" ng-controller="MyController"> <div id="tab-1" class="tab-pane fade active in " ng-i ...

Experiencing Elevated CPU Usage and Memory Capacity Exceeded Problem during npm run build in Laravel with Vue.js utilizing Vite

Currently, I am encountering a severe challenge while working on a Laravel project that incorporates Vue.js with Vite as the build tool. The issue arises when I run npm run build, causing the CPU usage to skyrocket to 100%. This ultimately leads to a deple ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Issues with loading content in jQuery's ajax() function

Having an issue with the ajax() function in jQuery. It seems like a simple problem, but I'm struggling to figure it out. My goal is to load content from another HTML file using ajax and here's the code I have so far: $(function(){ $('.submi ...

Choosing a populated control using JavaScript results in an empty value

Within my ASP.NET applications, I incorporate a server-side HTML select control. <select id="CompanyDropDown" runat="server" style="width:330px"> </select> To populate and pre-select items in this control, I use a JavaScript function triggere ...

The bootstrap function for showing the modal with the ID "myModal" is malfunctioning

As someone who is just getting started with PHP and Bootstrap, I am running into an issue where the modal doesn't seem to work when triggered using the .modal method. Here is the PHP code I am using: if ($show_login_modal) { echo " <scr ...

Can React components be saved in an array?

I am currently working on enhancing the code snippet provided below. This code is intended to iterate through elements of an array using keys to locate images within a lengthy SVG file directly embedded in the document under the identifier "SomelongUglySVG ...

How can I use lodash to locate and include an additional key within an array object?

I am looking to locate and insert an additional key in an object within an array using lodash. I want to avoid using a for loop and storing data temporarily. "book": [ { "name": "Hulk", "series": [ { "name": "mike", "id": " ...

morris.js - displaying a dynamic line chart using JSON data

These are the resources I have: clicks.json index.html The contents of my clicks.json file: [ {"day":1,"clicks":"387"}, {"day":2,"clicks":"432"}, {"day":3,"clicks":"316"}, {"day":4,"clicks":"238"}, {"day":5,"clicks":"354"}, {"da ...

Modifying the width of a jQuery UI dialog from within the dialog box itself

I have designed an ASP.Net web page with a div and iFrame to display another page within it. Now, I am wondering if there is a way to change the width of the dialog from a button inside the dialog itself... Is this achievable? Thank you. ...