The passed index in the Vue component does not match the anticipated values

This is the code snippet for my custom component:

<template>
    <span class="pt-3">
        <GoodMacroElement v-for="goodMacro in goodMacroData" :macro="goodMacro" :index="counter++" class="row mt-3"></GoodMacroElement>
    </span>
</template>

<script>
import GoodMacroElement from "./GoodMacroElement"

export default {
  components:{
    GoodMacroElement
  },
  name: "goodMacros",
  data(){
    return {
      name: 'GoodMacros',
      goodMacroData: null,
      counter:0
    }
  },
  beforeMount() {
    this.goodMacroData = window.GOOD_MACROS;
  },
}
</script>

<style scoped>

</style>

In this code, I am trying to pass a number starting from 0 using the prop named index to the child component. However, when I check the value of index in each GoodMacroElement, the first one has index = 909. How can I correct this to start the index value from 0?

Answer №1

Utilize the index provided by Vue itself.

<div v-for="(item, index) in items" :key="item.name"></div>

const { createApp } = Vue;

 createApp({
    data() {
      return {
        goodMacroData: [
          {name: 'macro A'}, {name: 'macro B'}
        ]
      }
    }
  }).mount('#app')
  
<script src="https://unpkg.com/vue@3"></script>

<div id="app">
  <div v-for="(goodMacro, index) in goodMacroData" :key="goodMacro.name">
    {{ index }}: {{ goodMacro.name }}

  </div>
</div>

Explanation:

When utilizing reactive variables in templates, and the variable is changed, Vue will automatically re-render the template for you.

In the provided example, the reactive variable counter was used in the template. This means that if anything modifies the value of counter, Vue will re-render the template and the v-for loop.

The problem arises from the fact that counter is being mutated within the loop - via counter++

Thus, every time Vue renders the list, the underlying reactive data is altered, causing Vue to re-render the list again, thereby updating the counter and repeating the process. Each time, counter commences at the value it ended with in the previous render.

Upon pressing the button, counter++ is executed, resulting in a re-render of the list and an increase in all the counts.

const { createApp } = Vue;

 createApp({
    data() {
      return {
        counter:0,
        goodMacroData: [
          {name: 'macro A'}, {name: 'macro B'}
        ]
      }
    }
  }).mount('#app')
    <script src="https://unpkg.com/vue@3"></script>

    <div id="app">
      <div v-for="goodMacro in goodMacroData" >
        {{ counter++ }}
      </div>
      
       <button @click="counter++">
          increment counter
      </button>
    
    </div>

You may have encountered warnings about maximum recursion in the console, as it leads to an infinite loop.

By utilizing the built-in index counter, you avoid mutating any values, thus preventing Vue from triggering a re-render.

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 steps can be taken to ensure that a function is executed in order to delegate the process forward?

In my JavaScript code, I have a series of functions that need to be executed in a specific order. One function may return a value synchronously, while others do not return anything or return an Observable result asynchronously. How can I ensure that each ...

Looking for guidance on integrating Forms with VueX and script setup? Are you utilizing v-model in your implementation?

UPDATE: I'm contemplating whether or not to abandon VueX entirely due to its outdated status, with Pinia being the preferred choice nowadays. Can someone confirm this? https://stackblitz.com/edit/vue-script-setup-with-vuex-hmrk5d?file=src/store.ts ...

When using ESLint together with React, you may encounter errors related to `no-unused-vars

I've configured eslint and eslint-plugin-react. After running ESLint, I'm encountering no-unused-vars errors for all React components. It seems that the linter is not recognizing JSX or React syntax. Any solutions? For example: app.js import ...

What could be causing the issue with ng-show in Angular?

When a user clicks on an icon, I want to display a drop-down menu. I attempted to use the ng-show directive for this purpose, but unfortunately, the drop-down menu is not appearing. I created an icon ..., and when clicked, I attempted to open the drop-do ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

react.js function that returns 'undefined'

Having trouble with my class function that returns undefined when I try to use the return value. Main.js: let db = new Database() let username = db.get() return( //returns undefined <p>{username}</p> ) database.js: class Database { [... ...

Having issues with the Jquery tablesorter plugin when attempting to prevent headers from being sorted

Can anyone help me with a sorting issue I am having with a table on my website? I am using the jQuery plugin tablersorter to sort the table, but I have two headers that I do not want to be sortable. I tried to disable them using the example provided on the ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...

Using ESLint to enforce snake_case naming conventions within TypeScript Type properties

When working with TypeScript, I prefer to use snake_case for properties within my Interfaces or Types. To enforce this rule, I have configured the ESLint rule camelcase as follows: 'camelcase': ["error", {properties: "never"}], Even though the E ...

The fixed sidebar refuses to pause before reaching the footer

I am facing an issue while building my blog. I am trying to figure out how to make my sidebar widget sticky and stop scrolling before reaching the #footer section. My widget is overlapping my footer and it would be really helpful if someone could assist m ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

Update elements dynamically using JSX

I have an array called data.info that gets updated over time, and my goal is to replace placeholder rendered elements with another set of elements. The default state of app.js is as follows: return ( <Fragment> {data.info.map((index) =&g ...

Populating fields in a new AngularJS document from a table

I have a project where there is a table displaying different instances of our service, and each row has an info button that opens a form with the corresponding row's information autofilled. However, I am facing an issue where by the time I retrieve th ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

Leverage the OpenWeather Icons to Pinpoint Locations on a Leaflet Map

Having some trouble incorporating weather icons from an openweather API call as markers on my leaflet map. The icons should appear in a popup on the marker within an img tag. However, despite confirming the correct icon URL through console.log, they only ...

Initializing an Express app with JSON file loading

My movie-finding application relies on backend API calls to function. As part of the initialization process, I need to load two JSON files: one containing a list of languages for searching (lang.json) and another stored in the config variable that provides ...