Does the Array Splice method always remove an item from the end?

I'm having trouble with deleting an item from an array using Array.splice. It seems to always delete the item from the end instead of where I want it to be removed. I'm working with Vue.js and dynamically adding items to an array, but when I try to remove them, they are deleted from the last position. Can anyone help me figure out why this is happening? Here is the code snippet:

<template>
<div>
    <span class="badge badge-pill mb-10 px-10 py-5 btn-add" :class="btnClass" @click="addBtn"><i class="fa fa-plus mr-5"></i>Button</span>


        <div class="block-content block-content-full block-content-sm bg-body-light font-size-sm" v-if="buttons.length > 0">
            <div v-for="(item, index) in buttons">
                <div class="field-button">
                    <div class="delete_btn"><i @click="remove(index)" class="fa fa-trash-o"></i></div>
                    <flow-button v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"></flow-button>
                </div>
            </div>
        </div>
    </div>
</div>
</template>
<script>
    import flowButton from '../assets/flow-button'

export default {
    name: "textArea",
    props:{
        index : Number
    },
    data() {
        return {
            buttons : [],
            btnClass : 'badge-primary',

        }
    }
    components : {
        flowButton
    },
    methods : {
        addBtn () {
            if(this.buttons.length >= 2) {
                this.btnClass = 'btn-secondary'
            }

            if(this.buttons.length < 3) {
                this.buttons.push({
                    title : ''
                });

            }
        },
        remove(index) {
            this.buttons.splice(index, 1)
        }
    }
}
 </script>

Answer №1

It seems that the issue may be related to the flow-button. I attempted to reproduce your error but ended up with this code instead. By replacing the flow-button with an input, the code now functions correctly. Please see the updated code below.

Ensure to use v-bind:key="index" when updating a list of elements in Vue rendered with v-for. By default, Vue employs an "in-place patch" strategy, meaning it patches each element without rearranging them to match the order of data items. This behavior is similar to track-by="$index".

A missing comma was found between 'data' and 'components'. I have removed the component causing no errors. Also, remember not to mix double quotes with single quotes for better consistency.

<template>
<div>
<span class="badge badge-pill mb-10 px-10 py-5 btn-add" :class="btnClass" @click="addBtn"><i class="fa fa-plus mr-5"></i>Button</span>
  <div class="block-content block-content-full block-content-sm bg-body-light font-size-sm" v-if="buttons.length > 0">
    <div v-for="(item, index) in buttons" v-bind:key="index">
      <div class="field-button">
        <div class="delete_btn"><i @click="remove(index)" class="fa fa-trash-o">sdfsdff</i></div>
        <input type="text" v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"/>
      </div>
    </div>
  </div>
</div>
</template>
<script>
export default {
  name: 'textArea',
  props: {
    index: Number
  },
  data () {
    return {
      buttons: [],
      btnClass: 'badge-primary'
    }
  },
  methods: {
    addBtn () {
      if (this.buttons.length >= 2) {
        this.btnClass = 'btn-secondary'
      }
      if (this.buttons.length < 3) {
        this.buttons.push({
          title: ''
        })
      }
    },
    remove (index) {
      this.buttons.splice(index, 1)
    }
  }
}
</script>

Answer №2

It appears that there could be a conflict with the index prop in your component. Consider using a different name for the index in your v-for loop:

<div v-for="(item, ind) in buttons">
    <div class="field-button">
        <div class="delete_btn"><i @click="remove(ind)" class="fa fa-trash-o"></i></div>
        <flow-button v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"></flow-button>
    </div>
</div>

Answer №3

Give this a shot. Properly deleting an item using the following method.

<div v-for="(item, ind) in buttons" :key="JSON.stringify(item)">

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

Tips for eliminating nested switchMaps with early returns

In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve th ...

`Unveil the hidden edges of the Google timeline chart`

Does anyone know how to remove the chart border from a Google timeline chart using this script? <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

What is the best way to link data from SQL Server to an HTML webpage?

Seeking assistance on how to display data from a SQL Server database in an HTML page using JavaScript, AJAX, and jQuery without the need for C#, PHP, VB.NET etc. Can someone please provide some reference links or share example code? ...

What is preventing me from accessing the sub-elements of an AngularJS controller?

I know this question has probably been asked countless times before, but I'm struggling to find the right words to explain my specific issue. Essentially, I'm having trouble accessing something like $ctrl.thing.subelement. However, the following ...

Creating a login feature using Laravel API and VUE client: A step-by-step guide

Currently, I am developing an application in VUE that requires users to log in for access to certain information. The login process is managed through a Laravel API which retrieves data from a database. When it comes to transmitting the user input from th ...

What are the steps to integrate the aws-iot-device-sdk NPM module with Angular 11? I am encountering errors related to fs, path, and tls during the build process

I manage a browser-based Angular application that was previously on version 5.6. This app consists of two components that subscribe to an IOT topic and listen for updates without publishing. The task at hand is to upgrade to Angular 11.0.3, which I have c ...

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

ERROR: Running out of memory in JavaScript heap while executing a command with "npm"

Encountered a fatal error (FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory) while attempting to execute any npm command. The error persists even with the simple "npm -v" command. I ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

Fetching JSON object from a node.js/express server using AJAX request

I've implemented server-side code to fetch data from an external website and return a JSON object to the client side of my node.js/express application. The intention is to further process this JSON on the client side. Within my index.js file, I have ...

The Pinia store appears to be malfunctioning when deployed to the server, yet it functions properly when served by V

Issue: After deploying my vue3 app with a Pinia store to a server, the page that accesses the store fails to display. This problem occurs on Firebase (both emulator and live site) as well as on Netlify. I suspect there may be a simple explanation hidden in ...

Uncheck the previous option selected in a multi-select dropdown using jQuery

Hey there, I've been facing an issue with my change handler when trying to add or remove values from an Array. It works fine until the last element is selected, at which point the change event does not fire properly. Has anyone else encountered this p ...

The Chartjs bar graph fails to display data upon initial page load

My HTML page includes a bar chart created using the ChartJS library. However, upon loading the page, the chart appears empty without displaying the data I provided and without rendering the bars. It only responds after clicking on the legend - first displa ...

JavaScript is proving to be uncooperative in allowing me to modify the

Despite searching through previously asked questions, I have been unable to find a solution to my issue. I am struggling with changing an image source upon clicking the image itself. The following is a snippet of my HTML code: <img id="picture1" oncli ...

Encountered an error stating "Cannot access property FindAll() of undefined" while working with a node/express JS app

Hey everyone, I'm encountering a problem with my express JS application and I'm not quite sure how to fix it. I'm working with an existing mySQL db and attempting to fetch items from my tbl_person table in the myDB database. As a newbie to t ...

Tips for establishing and connecting numerous connections among current nodes using the same criteria

While browsing StackOverflow, I came across similar questions. However, I believe this one has a unique twist. The main issue at hand is: How can I establish multiple relationships between existing nodes? I have the following code snippet: session . ...

Guide to merging two endpoints in express.js to create a single endpoint

I currently have 2 existing endpoints named /balance and /transactions. What is the most effective approach to create a new endpoint called /balance-and-transactions without having to refactor the existing code? For example: a('/balance', () =&g ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...