Search code examples
vue.jsvue-componentv-for

List of components not updating


I have this template displaying a list of components:

<template>
  <v-container id="container">
    <RaceItem v-for="(item, index) in items" :key="item + index" />
  (...)

When the array "items" is updated (shift() or push() a new item), the list displayed is not updated. I'm sure I'm missing something on how Vue works... but could anyone explain what's wrong?


Solution

  • The key attribute expects number | string | boolean | symbol. It is recommended to use primitives as keys.

    The simplest usage is to use a primitive unique property of each element to track them:

     <RaceItem v-for="item in items" :key="item.id" />
    

    ... assuming your items have unique ids.


    If you use the index as key, every time you update the array you'll have to replace it with an updated version of itself (i.e: this.items = [...items]; - where items contains the mutation).

    Here's how your methods would have to look in that case:

    methods: {
      applyChangeToItem(item, change) {
        // apply change to item and return the modified item
      },
      updateItem(index, change) {
        this.$set(
          this.items, 
          index, 
          this.applyChangeToItem(this.items[index], change)
        );
      },
      addItem(item) {
        this.items = [...this.items, item];
      },
      removeItem(index) {
        this.items = [...this.items.filter((_, i) => index !== i)];
      }
    }