Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Vue use it's “in-place patch”, though I'm binding a key in v-for loop?

I want to generate a dynamic list of Vue components with a v-for-loop. In that loop I'm passing data which is used by the components and also in some child-components among them.

The items of the list can be deleted individually. So to avoid the “in-place patch” (https://v2.vuejs.org/v2/guide/list.html) which would mess up the child components I'm binding a key to the for-loop. But it doesn't work.

<div v-for="(shift, index) in shifts"  v-bind:key="index">
  <hr>
    <Shift v-bind:shiftdata="shifts[index]" v-on:DeleteShift="DeleteShift" />
  <hr>
</div>

If i'm now deleting a component which is in the middle, the child components of it will be rendered into another component.

Another thing that confuses me is, that if I take "shift" instead of "index" as the key, it works fine. But than I'm getting warnings because the "key is a non-primitive value" and "duplicate keys detected".

like image 655
SunnySide Avatar asked Oct 16 '25 05:10

SunnySide


1 Answers

This happens because keys are identifiers to the items rendered in a for loop. They help preventing the rerendering of everything when one element changes.

Now, assume you have the following shifts array:

shifts = [{a: 10}, {a: 20}, {a: 30}]

When you render these with their index as the key, you're identifying, {a: 10} by 0, {a: 20} by 1, {a: 30} by 2 and so on.

When you delete a shift, say {a: 20}, the shifts array becomes:

shifts = [{a: 10}, {a: 30}]

and the elements are identified as follows: {a: 10} by 0, {a: 30} by 1.

Earlier, key: 1 was for {a: 20} but now it is for {a: 30} which confuses vue.

This is why indexs are a bad thing to use as keys. keys are generally supposed to be unique identifiers for an element, something like database id.

If you have any such entity in your shift object, I'd suggest you use that as your key

Hope this made sense

like image 51
SerShubham Avatar answered Oct 17 '25 20:10

SerShubham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!