What causes Vue to drop nested component data within a v-for loop?

Witness the mysterious behavior through my fiddles:

Anticipated outcome:

https://jsfiddle.net/o7c9mwzf/27/

By clicking "unshift," I add an element to the beginning of my items array. After setting its data, clicking "unshift" again should maintain the element’s position and data.

Surprising result:

https://jsfiddle.net/o7c9mwzf/25/

In this fiddle, the component is enclosed within a div where the v-for directive is placed on the div itself:

<div v-for="item in items"><comp :key="item.uuid"/></div>

Unexpectedly, when I unshift the array, existing items lose their associated data.

Can you shed light on this peculiar behavior? The documentation has been of little help.

Answer №1

Make sure to place the key on the root component of the v-for element - in this scenario, it should be on the div, not the comp

<div v-for="item in items" :key="item.uuid"><comp /></div>

Alternatively, you can apply the :key attribute to the comp if utilizing a template instead

<template v-for="item in items" :key="item.uuid"><comp /></template>

By providing a unique key, Vue is able to efficiently manage each node's identity for element reusability and reordering

Source: https://v3.vuejs.org/guide/list.html#maintaining-state

If the key is placed on the comp, the state within the parent element (div) will not be preserved.

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

"Adding a Vue component into a contenteditable div: A step-by-step guide

Looking to develop a simple wysiwyg editor with Vue, I came across only one fully-fledged wysiwyg editor built on vue.js at https://quasar.dev/vue-components/editor. However, I couldn't find the ability to insert images there. Most other Vue wysiwyg e ...

Retrieve the country code of an IP address using getJSON

I am currently facing an unusual issue. My goal is to extract the country code (like US for United States) from an IP address using free APIs. After some research, I came across ipify for retrieving the IP address (which works fine), and then attempted to ...

Different ways to split up information on the client side into separate "pages"

Looking for a way to split a lengthy HTML text-only article into multiple divs for easier page navigation on mobile devices? Perhaps dividing it into separate pages that users can swipe through on their iPad or iPhone? I've experimented with JavaScri ...

Keep JS Accordion open when links are clicked

Utilizing PHP, I am fetching items from a database and creating an HTML table to display each item. Adjacent to the HTML table, there is a side menu with an accordion function implemented in JavaScript. Within each accordion section, there are links for ...

Transform a Vue JS Typescript object into an array and then back into an object through iteration

Having an object that contains an array of objects, I am looking to extract the data from each object in the array to show the opening hours. I have successfully accessed each key value within a for loop in the code snippet. However, I am unsure about how ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Mac users may experience lag when using Javascript parallax effects

I created a parallax page where the background image changes using JavaScript translateY(- ... px)' similar to what you see on the firewatch website. On Windows, the parallax effect works smoothly. However, on macOS it is smooth only in Safari. All ...

Can you explain the distinctions between Rundeck and Quartz in terms of their job scheduling capabilities?

In my quest for a job scheduler compatible with both node.js and Rundeck, I stumbled upon Quartz. However, despite my efforts to grasp the differences between Quartz and Rundeck, I find myself at a loss. Any assistance on this matter would be immensely a ...

Synchronize the completion of multiple promises in ExpressJs before sending a response

My POST API contains some logic that needs to wait for all promises to finish before sending the response. However, I'm facing an issue with making my server wait using await Promise.all(tasks); I've tried various approaches and even used librar ...

every cell should be painted a distinct hue

I need to create a 10x10 array in JavaScript and fill each cell in the 2D array with different colors using canvas. I have managed to do this part, but now I am stuck on how to check if each cell has a different color from its neighbors. Any suggestions ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

Switching a jQuery AJAX Response

Currently, I am utilizing an AJAX function to retrieve and display specific categorical posts when a corresponding button is clicked: <script> // Brochure AJAX function term_ajax_get(termID) { jQuery("#loading-animation").show(); ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

Accessing variables from an external script in jsdom

Here is a simple example of jsdom code using the script parameter. Despite my best efforts to reference external JS files, I keep running into this issue: ReferenceError: exVar is not defined Does anyone know what might be causing this problem and how ...

Using the <pre> tag with Vue.js in v-html allows for displaying pre

When using v-html to display content retrieved via AJAX, I encountered an issue with the "pre" tag not rendering as expected. Here is my component setup: <div v-html="content"></div> For example, the content includes: <h1>Title</h1 ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

Navigating to redirected URL within jquery's get() function

When I tried sending a get request to a Google App Script URL in my application using JQuery's get method, everything was working fine. However, out of the blue, that API started redirecting to a different URL in case of an authentication error. As a ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...