The results did not meet expectations when utilizing the incremental value within the loop

I need help finding a way to create a sequential counter for my nested loop. I attempted the following test:

<template>
  <div class="container">
    <ul>
      <li v-for="item in list" :key="item">{{ counter++ }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Foo",
  data() {
    return {
      list: ["item 1", "item 2", "item 3"],
      counter: 0
    };
  }
};
</script>

Instead of returning 1,2,3, it displays as 303, 304, 305 and triggers this warning:

You may have an infinite update loop in a component render function.

I am aware that I can use (item, index). However, in my real code, I have a nested loop.

https://codesandbox.io/s/amazing-mcnulty-hou4p

This is an example of my actual situation with a nested loop:

<template v-for="ranking in daysImages[currentDay]['images']">
    <template v-for="image in ranking">
        <figure class="thumb"
            v-for="path in image.paths"
            :key="path"
            @click="openModal()"
            v-show="
            (selectHashTag === allHashTagsTitle || image['hashtags'].includes(selectHashTag)) &&
            (selectTag === allTagsTitle || image['tags'].includes(selectTag))"
        >
            <img :src="path | formatImageURL" alt="">
        </figure>
    </template>
</template>

Answer №1

Why not try using .indexOf(item) on your array to obtain the item's actual index rather than relying on the Vue functionality? This way, you can get the accurate index without having to use counter++ which increments it after each render.

Answer №2

One option is to create a non-reactive property, or you can set an index on each item before rendering:

If you choose the latter option:

  • You could flatten your 2D array into a 1D array (and easily access the id based on its position in the array)
  • Alternatively, you can calculate the id yourself and assign it to each element before rendering the grid.

let Grid = {
    props: ['arr2d'],
    data () {
      return {
        arr1d: this.arr2d.flatMap(x=>x)
      }
    },
    template: `
      <ul>
        <li v-for="(fruit, counter) in arr1d">
          {{fruit}}: {{counter} 
        </li>
      </ul>
    `
  }
  let Grid2 = {
    props: ['arr2d'],
    data () {
      let z = 0
      return {
        indexedArray: this.arr2d.map((ranking, i) => {
          return ranking.map(im => {
            return { image: im, id: z++ }
          })
        })
      }
    },
    template: `
      <ul>
        <template v-for="ranking in indexedArray">
          <template v-for="({image, id}) in ranking">
            <li>{{image}}: {{ id }}</li>
          </template>
        </template>
      </ul>
    `
  }
  new Vue({
    components:{ Grid, Grid2 },
    template: `<div>
      <Grid :arr2d="[['apple','grodzi', 'orange'], ['lime', 'lemon']]"/>
      <Grid2 :arr2d="[['apple','grodzi', 'orange'], ['lime', 'lemon']]"/>
    </div>`,
    el:'#app'
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></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

The "flickering" effect of the div is like a dance, moving gracefully between fade outs and

I am encountering a similar issue as described in this thread: same problem (fiddle: original fiddle). However, I am still learning JavaScript and struggling to apply the solution provided because my HTML code is slightly different. Can someone please assi ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

A substitute for iframe in ReactJS

I am currently using an iframe to embed Bing Translator and Bing Images onto my website. However, I need to find an alternative to iframes because a specific library I'm utilizing cannot detect them. What are some options for embedding websites onto m ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

Converting a mongoDB response array from a JavaScript object to a JSON string: a step-by

After developing a custom javascript API to retrieve data from a MongoDB database, the issue arose where the data is being returned as an array of objects instead of a simple JSON string. The current statement used for retrieving the objects is: return db ...

Employ Angular within the parameters of a JavaScript function call

My goal is to incorporate Google Maps into my webpage for various locations (lieux). Within the HTML page, I have the necessary function set up for Google Maps. <script> function initialize(long,lat) { var mapCanvas = document.getElementById( ...

Is it possible to temporarily change the state and then revert it back to its original state by utilizing settimeout?

I'm trying to temporarily set the value to true for one second and then revert it back to false using setTimeout, but I'm encountering an issue with my code. Here's what I have so far: const [value, setValue] = useState(false) const handleCl ...

Capturing link titles for control navigation in Nivo Slider

Essentially, in the nivoslider plugin, the controlnav section displays numbers based on the "rel" attribute in the code. I am wondering if there is a way to modify this so that it retrieves the "title" or "alt" from the link added to the slideshow. This wo ...

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...

Retrieving data with comparable column values using pattern matching

I have a table called cities which contains various records such as: Name Value id 62 name New York id 63 name Paris id 64 name Tokyo There are many more records but the structure remains consistent. In my Node.js API, I receive a city n ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Preloading and rendering an image onto a canvas in a Vue single-page application is not functioning as expected

I am working on a Vue 3 SPA where I am manipulating canvas elements. To preload my image, I am using the function provided below: async preloadLogo () { return new Promise( (resolve) => { var logo_img_temp = new Image(); const logo_s ...

exporting a freshly made object every time

I am trying to export a file that contains an object with a unique reference each time it is imported. Currently, when two files import this single export, they share the same reference and changes made in one file reflect in the other as well. I attempted ...

Puppeteer - merging the power of CollectionView and View

I've recently started using Marionette and I'm looking to create a CollectionView within another CollectionView. I came across information stating that when a view receives a collection as an argument, it is stored as 'items' argument. ...

How can Vue JS be used to assign numbers to specific elements in an array that meet certain conditions?

Imagine having an array of objects within your Vue state like the following: [ {name: "Daniel", default: false}, {name: "Ross", default: true}, {name: "Rachel", default: false}, {name: "Joey", default: false} {n ...

Tips for incorporating a multiple tag search feature within my image collection using JavaScript?

I am facing a challenge with my image gallery search feature. Currently, users can search for images by typing in the title or tag of an image. However, I need to enhance this functionality to allow for multiple tags to be searched at once. For example, if ...

How can I prevent my service worker from caching text/html documents such as the index page?

When my PWA is offline, I want it to display the offline.html page. However, even when the homepage fails to fetch due to being offline, my service worker still uses cached text/html requests to retrieve the homepage. To create my PWA, I am utilizing work ...

What is preventing my Express.js from running properly?

My express.js application stops running after reaching this point: node app.js info - socket.io started I'm looking for guidance on why this error occurs and how to resolve it. It seems like the issue lies within my app.js file, which I've inc ...

Creating a JSON object from text using JavaScript is a straightforward process

Looking to generate an object using the provided variable string. var text ='{"Origin":"Hybris","country":"Germany","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...