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.