Blog>
Snippets

Optimizing List Rendering with Keys

Provide an example of rendering a list using v-for with and without the key attribute, demonstrating how keys aid in efficient VDOM updates.
<template>
  <!-- Without the key attribute -->
  <ul>
    <li v-for="item in items">{{ item }}</li>
  </ul>

  <!-- With the key attribute -->
  <ul>
    <li
      v-for="(item, index) in items"
      :key="index"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: ['Apple', 'Banana', 'Cherry'] // Sample list items
    };
  },
  // Methods to manipulate the list can be added here
};
</script>

<style>
  li {
    list-style-type: none;
    margin: 5px 0;
    padding: 5px;
    background-color: #f0f0f0;
  }

  ul {
    padding: 0;
  }
</style>
This code demonstrates how to render a list with and without using the key attribute in Vue.js. The key attribute provides a unique identifier for each list item, allowing Vue to track each one individually for efficient updates. Without the key attribute, Vue doesn't have a reliable way of identifying nodes in the DOM, which might lead to incorrect DOM updates. With keys, Vue can determine what has actually changed, only updating those specific DOM nodes, thus improving performance.