Blog>
Snippets

Fragment with Keyed Elements

Show how to provide a 'key' to elements within a fragment for proper reactivity and state updates in Vue.js.
// In Vue.js 3.x, you can provide keys to elements within fragments using the <template> tag.

<template>
  <div id="keyed-fragments">
    <template v-for="item in items" :key="item.id">
      <!-- Use the item's unique id as the key -->
      <h3>{{ item.title }}</h3>
      <p>{{ item.description }}</p>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // Sample array of items, each with a unique ID
      items: [
        { id: 1, title: 'Item 1', description: 'Description for item 1' },
        { id: 2, title: 'Item 2', description: 'Description for item 2' },
        // more items...
      ]
    };
  },
};
</script>
This code snippet is a Vue.js component using a fragment (the <template> tag with v-for directive) to render a list of items. Each child element within the fragment is given a unique 'key' attribute using the item's 'id', which is necessary for Vue.js to keep track of each element's identity for efficient re-rendering.