felipeecst
felipeecst

Reputation: 1415

VueJS: v-for with dynamic component strange behavior

I have the following syntax inside one of my components:

<event-item v-for='(event, index) in events'
            :is='eventComponent(event)'
            :key="'event-' + index"
            :event='event'>
</event-item>

The list is rendered correctly at the first moment.

However, when I add a new element to the events array using events.unshift(event), a strange behavior happens: the event-item component for the event with index n is rendered using some of the properties of the event with index n+1.

This behavior also does not occur if I use events.push(event), but using it is not an option because I need to insert the new events at the beginning of the list.

Upvotes: 1

Views: 90

Answers (1)

webnoob
webnoob

Reputation: 15934

This is happening because of the key you are using and the fact you are unshifting items out of the array. Because that key has been used, the component won't re-render.

You have 2 options:

  1. Change your key so it contains an ID of event (I would recommend this approach). You can generate an ID using a Guid or something.
  2. Clear the array and re-build it (wasteful IMO)

I personally have a uuid package in my projects but you could do something like:

event.id = '_' + Math.random().toString(36).substr(2, 9)

then in the component v-for loop: :key="event.id"

Upvotes: 2

Related Questions