Reputation: 1012
I have such a template in Vue:
<AutoTaskBlock ref="block" v-for="(block, index) in 2" key="index" class="block"></autoTaskBlock>
<AutoTaskCircle ref="block" v-for="(circle, index) in 3" key="index" class="circle"></autoTaskCircle>
So i do have two lists of components which are created "from air" - i do not use any array to create it from it - in this helps me ability to use "v-for="anything in (int)". However vue warns me that any list made by v-for needs unique key. I wanted to use index, but it is duplicated and this gives me no warning but error. My next attempt was to use some random value computed in
computed: { rand() { return Math.random()*100 } }
but using it like this:
<AutoTaskBlock ref="block" v-for="(block, index) in 2" key="rand" class="block"></autoTaskBlock>
<AutoTaskCircle ref="block" v-for="(circle, index) in 3" key="rand" class="circle"></autoTaskCircle>
..results the same error. After checking - computed "rand" is randomized only when created, not later so each is the same. Next attempt was to create method of rand like this:
methods: { rand: function() { return Math.random()*100 } }
But same - duplicate key error appears. Is there a way to use two lists like this and give them a unique key?
thanks, Kalreg:
PS: same ref in both components is as i desired, so no error here.
Upvotes: 2
Views: 10710
Reputation: 215057
One options is to prefix index
with a unique word for each list you are creating to deduplicate; For your case something like 'block' + index
and 'circle' + index
:
<AutoTaskBlock ref="block" v-for="(block, index) in 2" :key="'block' + index" class="block"></autoTaskBlock>
<AutoTaskCircle ref="block" v-for="(circle, index) in 3" :key="'circle' + index" class="circle"></autoTaskCircle>
Upvotes: 7