How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image.

This functionality is implemented in the upload.vue file:

<template>
<div>
<div>
//Universal category select. this selection will apply to all comp.
<v-select  placeholder="Select Category"
          class="mt-2 md:w-1/2"
...

In addition, users can choose a single category that will be applied to all components on the page using the fileUpload.vue component:

<template>
  <div>
    
      <div class="m-4">
        <form
          @submit.prevent="uploadImage"
          ...

However, there are some issues that need to be addressed:

1. When a user removes a component from the page, the selected Category/Type remains in the same position, causing inconsistency.

2. If a universal Category is chosen before selecting images, it applies to all components. However, after selecting images, the universal select option stops working.

3. The transition effects do not work on any of the components.

Answer №1

To ensure uniqueness, it is necessary to assign a distinct ID. Here's how you can achieve that:

Template Modifications: Start by replacing the usage of index with an id - setting an id ensures uniqueness. Therefore, set your :key to file.id (which will be created in the script) and pass your file along with deleteThisRow to your methods. That's it!

<div class="md:w-1/2" v-for="file in files" :key="file.id">

//change index to file here to reference the unique file created with the set id
@delete-row="deleteThisRow(file)"

Script Adjustments: In your data(), set id = null - this prevents your created id from being undefined. Next, go to your methods and set id = i - making it truly unique and immutable unlike the previous index. Lastly, use map on your files array to find the correct position indicated by indexOf which needs to be deleted.

//in your data
data() {
  return {
    id: null,
  }
},

//in your methods
methods: {
    uploadImage(event) {
      let file = event.target.files;

      for (let i = 0; i < file.length; i++) {
        this.files.push({image:file[i], id : i}); //setting id to a unique number here! (could be this.id, you need to test)
      }
    },
    deleteThisRow: function(file) {
      var indexDelete = this.files.map(x => {
        return x.id;
      }).indexOf(file.id);
      
      this.files.splice(indexDelete, 1);
    }
  }

Lastly, make sure to pass the file.id to your child using the following code:

<child  :uniqueID="file.id"
              :file="file.image">

and access it in your child component through props.

If I correctly understood your question, this solution should resolve your issue. Please confirm if it works for you!

Additional Note: Replace all references of index with file.id to ensure true uniqueness.

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 are the consequences of excluding a callback in ReactJs that may lead to dysfunctionality?

<button onClick = { () => this.restart()}>Restart</button> While going through a ReactJs tutorial, I encountered a game page which featured a restart button with the code snippet mentioned above. However, when I tried to replace it with the ...

What is the most efficient way to transfer an object between two functions in AngularJS?

As a beginner in AngularJS and Javascript, I recently attempted to pass an object from one function to another. Here is the HTML Code: <div ng-click="getValueFromHtml(userObj)">send Object </div> This is the Controller Code: $scope.getValueFr ...

Issues persist with $.getJSON

I apologize if this question has been addressed previously, but I couldn't find the answer I was seeking. My issue involves using $.getJSON to send variables to a PHP file. Although the file returns success as true, it always triggers the .fail functi ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

Implementing pagination in Webgrid using AJAX post method

I've developed this JavaScript code: function PartialViewLoad() { $.ajaxSetup({ cache: false }); $.ajax({ url: "/ControllerAlpha/MethodBeta", type: "GET", dataType: "html", data: { s ...

AngularJS textbox failing to recognize line breaks as expected

I am struggling with the following HTML code: <div class="form-group"> <div class="input-group col-sm-12"> <label for="" class="control-label">Comments</label> ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

"Utilize Bootstrap Modal to load dynamic content with Ajax and incorporate loading

When I use the Bootstrap Modal to load content from another page, the data is quite complex with multiple queries and dynamic forms. As a result, when the modal opens, it tends to get stuck momentarily. I am looking for some sort of animation or indicator ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...

What could be causing my script files to not load when I use ajax load() to bring external content into a #content div?

I am currently troubleshooting why my JS files, or script files, are not loading when I bring external content into the #content DIV. While the HTML and CSS load correctly, the scripts do not. Upon page load, my index page, complete with head, body, sc ...

Transform a value nested at any depth into an object key using Ramda or plain JavaScript

I have encountered a unique scenario while using a specific library. Instead of returning an array, this library returns nested objects with the final leaf node containing the value. For instance: red.walk.fast.true is returned as {red: {walk: {fast: &apo ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

Navigate through each element with a specific class name in a block of HTML code using

Currently, I am dealing with an HTML string that is being retrieved through AJAX. Let's assume it looks like this: var htmlString = '<div class="post"></div><div class="post"></div>'; I want to find a way to iterat ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: I'm curious, how can I implem ...

Transmitting information from directive to parent scope controller

I've successfully implemented a directive that generates a Google map on the page. Now, my goal is to pass the map object back out of the directive and into the parent controller. This will allow me to utilize it in various methods as needed. While ...

Leveraging Ajax with Google Analytics

Currently, I am working on a website that utilizes Ajax calls to update the main content. In order to integrate Google Analytics tracking code using the async _gaq method, I need to push a _trackPageview event with the URI to _gaq. There are two approaches ...

Divide the table row and store each cell using regular expressions

Here is the original source text: gi0/1 1G-Fiber -- -- -- -- Down -- -- Access gi0/2 1G-Fiber -- -- -- -- Down -- -- gi0/3 1G-Fiber -- -- -- -- Down -- -- gi0/4 1G-Fiber -- -- -- -- Down -- -- gi0/5 1G-Fiber -- -- -- -- Down -- -- gi0/0/1 1G-Fiber -- ...

Different ways to manipulate the CSS display property with JavaScript

Having trouble changing the CSS display property to "none" using JavaScript. Check out my code: <div class="mydiv" onClick="clickDiv1()">hello</div> <div class="mydiv" onClick="clickDiv2()">hi</div> <div class="mydiv" onClick=" ...