Deleting an item from a Vue.js list

I'm currently working on a project to develop a basic webpage that allows users to add or remove textboxes using vue.js.

new Vue({
  el: "#app",
 data() {
    return {
      list: []
    };
  },
  methods: {
    deleteFromList(index) {
      this.list.splice(index, 1);
    },
    addItem() {
      this.list.push({});
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>App</title>
    <meta charset="UTF-8" />
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
<body>
    <div id="app">
         <button @click="addItem()">Add 1</button>
      <ul>
          <li v-for="(item, index) in list":key="index">
            <textarea rows="1" cols="30">{{item}}</textarea>
            <button @click="deleteFromList(index)">Delete</button>
          </li>
      </ul>
    </div>

    <script src="index.js"></script>
  </body>
</html>

I've embedded the code snippet into the page (you may need to expand it for better visibility), but I've encountered an issue where clicking the Delete button removes the last row instead of the corresponding one. Can anyone provide guidance on resolving this error?

Many thanks for your assistance :)

Answer №1

Removing the correct item from the array is actually happening, but the change may not be visible because you are only updating the textarea value and not the model itself. The textarea is not directly linked to the value; it is just cached using :key="index". Here is an example that demonstrates this - by adding a counter, you can observe that the correct object is being deleted.

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data() {
    return {
      list: [],
      counter: 0,
    };
  },
  methods: {
    deleteFromList(index) {
      this.list.splice(index, 1);
    },
    addItem() {
      this.list.push(this.counter++);
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <button @click="addItem()">Add 1</button>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      <textarea rows="1" cols="30">{{item}}</textarea>
      <button @click="deleteFromList(index)">Delete</button>
    </li>
  </ul>

  <pre>{{ list }}</pre>
</div>

To ensure dynamic changing values/models, utilize v-model for the value and use indexOf when removing items.

Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
  el: "#app",
  data() {
    return {
      list: []
    };
  },
  methods: {
    deleteFromList(item) {
      this.list.splice(this.list.indexOf(item), 1);
    },
    addItem() {
      this.list.push('');
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  <button @click="addItem()">Add 1</button>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      <textarea rows="1" cols="30" v-model="list[index]"></textarea>
      <button @click="deleteFromList(item)">Delete</button>
    </li>
  </ul>
</div>

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

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

The Tailwind style did not completely translate when applied to the content of dangerouslySetInnerHtml

I have an HTML file containing Tailwind styles stored in my database, which needs to be fetched first. This will result in an HTML string that will be inserted into dangerouslySetInnerHtml. Here is the code snippet (utilizing Qwik): export const useHTML = ...

Getting started with html2canvas: A beginner's guide

So here's a seemingly simple question... I'm diving into new territory and stumbled upon http://html2canvas.hertzen.com with a straightforward tutorial. After successfully running the command npm install -g html2canvas, I hit a roadblock. Where e ...

Is there a way to determine whether a mouse-down event took place on the scroll-bar or elsewhere within the element?

Looking for a solution with my HTML div acting as a canvas containing various objects. The issue lies in the fact that when attempting to draw a selection rectangle by dragging with the mouse, if scroll bars appear due to the large size of the canvas, scr ...

Verify whether the default export of a file is a React function component or a standard function

Trying to figure out how to distinguish between modules exporting React function components and regular functions. Bun employs file-based routing, enabling me to match requests with module files to dynamically import based on the request pathname. Conside ...

HTML with embedded PHP script

i cannot seem to display mysql data in html format. the table i am working with is called App appid | app | version | date | apk file | 1 sample 1.0.0 2012-10-12 sample.apk //here is the mysql query ...

Using Python and Selenium to manipulate the webpage and execute JavaScript can help reconstruct the true HTML structure

I have a very basic Selenium code snippet that I am running: <input name="X" id="unique" value="" type="text"> <script> document.getElementById("unique").value="123"; </script> While I can retrieve the input value "123" using driv ...

Is there a way to get rid of the "bouncing effect" on my button while using an inline floating-label text input?

When an input with a floating label (Bootstrap 5) is inline with other elements, the elements may appear to jump up and down depending on the position of the floating label. https://i.sstatic.net/kDxBo.gif <link href="https://cdn.jsdelivr.net/npm/bo ...

Pressing the button will activate the Ctrl+z and Ctrl+y key commands

I have created two separate buttons for triggering actions equivalent to pressing Ctrl+z and Ctrl+y. I am attempting to make these actions occur with the click of a single button. However, when trying to set up the functionality to trigger Ctrl+z and Ctr ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Utilize the function with another function (difficult to articulate)

Apologies in advance for my beginner question. Review the code snippet below: var dt = new Date(t*1000); var m = "0" + dt.getMinutes(); Depending on the t variable (unix time), the output can be one of the following: m = 054 // 54 minutes m = 03 // 3 min ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

Ensure that the spacing between rows matches the spacing between columns

I am working on creating a 3x3 grid using Bootstrap. My goal is to have consistent spacing between the rows and columns. How can I achieve this effectively? ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

a non-breaking space within a hyperlink

While working on the subnavigation of a website, I encountered an issue with the link Suite «Mont Blanc», which was pulled from the backend. The desired format for this link was:       Suite «Mont Blanc» However, t ...

Securing your Laravel and Vue source code: Best practices

Recently developed a website using Laravel and Vue. Seeking advice on safeguarding the code from unauthorized copying (both PHP and VUE) while hosting the project on a VPS server? Specifically looking for ways to protect the code within the resources fol ...

Optimal ffmpeg configurations for encoding videos into mp4 and ogg formats for seamless playback on HTML5 platforms

Despite the buzz surrounding it, the HTML5 video tag is facing a minor issue. To ensure cross-browser compatibility, multiple video formats - like mp4 and ogg - need to be included for its use. Unfortunately, I couldn't find optimal settings for each ...

What is the reason for the omission of H1 tags from the table of contents list in NuxtJS's Content module?

Currently, I am facing an issue with importing a large amount of markdown content that heavily utilizes H1 (#) tags. While trying to create a table of contents (TOC) component, I noticed that the @Nuxt/Content package does not include H1 tags in the provid ...