Blog>
Snippets

Keyed v-for for Efficient Updates

Explain the importance of using keys in v-for for maintaining state and minimizing DOM manipulations during list updates.
<template>
  <div>
    <ul>
      <!-- Use v-for with a :key for efficient updates -->
      <li v-for="item in items" :key="item.id">
        {{ item.text }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, text: 'Item 1' },
        { id: 2, text: 'Item 2' },
        // More items...
      ]
    };
  },
  // Methods to update items...
};
</script>
This Vue.js template snippet demonstrates using 'v-for' with a ':key' to iterate over an array of items. The ':key' is bound to a unique identifier for each item, which allows Vue to track each node's identity and reorder existing elements when the list changes, rather than completely re-rendering the list. Efficiently updating the DOM in this way minimizes manipulation and maintains internal component state.