This is my 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>
I'm trying to pass a number that start from 0 using the prop named index, to the child component
<GoodMacroElement v-for="goodMacro in goodMacroData" :macro="goodMacro" :index="counter++" class="row mt-3"></GoodMacroElement>
But when I check index value on each GoodMacroElement the the first has index = 909¿?¿?¿ ,how I cam make it to make this value start from 0?
Use 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>
Reason:
When you use reactive variables in templates, and the variable is mutated, Vue will re render the template for you.
In your example, you were using the reactive var counter in the template. This means when anything changes the value of counter, Vue will re render the template, and your v-for loop.
The issue is, you were mutating counter in the loop - with counter++
So every time Vue renders the list, the underlying reactive data is changed, and Vue has to re render the list again, re updating the counter and so on. Each time counter starts at the value it was at the end of the last render.
You can see here - pressing the button simply runs counter++ and you can see the list re render and all the counts go up.
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 probably had some warnings about maximum recursion etc in the console as its an infinite loop.
Using the built in index counter, you do not mutate anything thus Vue does not re render.