The VueJS v-for loop encounters a problem when the values within the array are identical

Check out my pen here: http://codepen.io/leetzorr/pen/aprZqO

This is the HTML code:

    <template v-for="spot in bars" :key="item.$index">
      <div id="bar-holder">
    <div class="bars">
      <ul>
        <span>{{ $index }}</span>
        <li v-for="n in bars[$index]"></li>
      </ul>
      <button v-on:click="increase($index)">+</button>
    </div>
  </div>
  </template>

And this is the JavaScript code:

var par = {
  bars : [ 1, 5, 6 ]
}
var cl = new Vue({
  el: '#container',
  data: par,
  methods: {
    increase: function (index) {
      var value = this.bars[index];
      value++;
      par.bars.$set(index, value);
    },
  }
})

Clicking the increase button under each group of bars will increment the value in the par.bars array. However, there seems to be a bug where one of the bar elements disappears when the value matches that of another sibling element.

I've spent hours reviewing my code but can't seem to pinpoint where the issue lies.

Answer №1

Substitute

<template v-for="item in products" :key="item.$index">

with:

<template v-for="item in products" :key="item.$index" track-by="$index">

For more details, refer to the Vue.js documentation:

Answer №2

The reason for this behavior is that Vue reuses templates with the same key.

To prevent this, one solution is to use the index as the key (which appears to be what you originally intended to do!)

To achieve this, update the v-for directive in your template to something like:

<template v-for="spot in bars.length">

You can view a working example in this code snippet.

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

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

What is the best way to make a request to the deployed API on Vercel?

Here is the structure of my files: root client index.js package-lock.json package.json routes.js Upon sending a request to my API, I receive a status code of 200 but an error message stating "You need to enable JavaScript to run this app." Both ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

How to save an image in Internet Explorer browser without opening it automatically

Is there a way to download an image in Internet Explorer using the <a> tag without it opening in a new tab? Since IE does not support the HTML5 <download> tag, I am looking for a solution to directly download the image instead of opening it. ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...

Having trouble with setting the date in Firefox 57 using Selenium 3.4?

Date Field Image Having trouble setting date information beyond the specified date field using the sendKeys function. Attempted to use JavaScript but unable to successfully set the value. Update: HTML driver.findElementBy("//label[text()='Past Spe ...

Creating a banner using four grid elements, with each element containing four child elements, is a simple process that can

Can you assist me in recreating my idea from an image? I am having trouble understanding how to select and place other elements, and then return them to their original positions after deselecting... I attempted to use a grid but it did not work properly. ...

Can you explain the functionality of express-async-handler?

Hello, I'm trying to understand the purpose of express-async-handler. I came across it in a repository I was exploring. According to the documentation, express-async-handler is a simple middleware designed to handle exceptions within asynchronous exp ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

Guide to transferring req.params to a callback function within node.js

I am currently working on a Node.js project using Express. I have been attempting to retrieve data using the NPM request package, utilizing a specific URL and passing an anonymous callback function to handle the resulting JSON file. The code below has bee ...

Tips for enhancing the efficiency of my JavaScript code?

On my page, I have a list of items with various actions assigned to them. One can either click on an icon next to each item or check a checkbox on the left side. However, when clicking on an action after selecting multiple items, there is a noticeable lag ...

Error: The module PosModel is not defined

Recently, I took over the responsibility of working on the models.js file for the point_of_sale module. My task was to add a new model by integrating the following code: openerp.dewieuw = function(instance, local) { //module is instance.point_of_sale var ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

The program detected an unfamiliar command named 'node_modules', which is not recognized as an internal or external command, operable program, or batch file

I have integrated gulp into my project. Successfully installed gulp Added the npm script Executed the script using "npm start" Encountered the following error:- **> start node_modules/.bin/gulp watch 'node_modules' is not recognized as an ...

Django: What is the best way to utilize AJAX for updating my database?

One feature of my web application is that users have a coin balance along with a timer. When the countdown timer reaches zero, I want the user's coin balance to go up. Within the Django framework, I access the user's coin balance using: {{ reque ...

Exploring the Beauty of Trees through Twitter Bootstrap

I've been exploring the creation of a tree structure (similar to a directory tree) using mainly CSS and minimal JS for things like states. I'm wondering if there are any reliable tree plugins available that work well with bootstrap or jquery-ui b ...

Utilizing Asp.net MVC to trigger a C# method from the client-side using an onclick JavaScript event

In my project, I have a "MultiLanguageProvider" class in C#. This class is not a Controller or Model. The goal is to have a functionality where when a user clicks on <a href="">Change language</a>, it should trigger the server-side method void ...