Home > OS >  Get Loop Key Inside Vue SFC
Get Loop Key Inside Vue SFC

Time:05-19

Given the following looping component:

<MyComponent v-for="(item, i) in items" :key="i" :item="item" />

How do I get the value of key within MyComponent obviously key is a reserved word so it fails to work as a prop.

CodePudding user response:

Pass it as a declared prop (e.g: index):

<MyComponent v-for="(item, i) in items" :key="i" :item="item" :index="i" />

MyComponent.vue:

export default {
  props: {
    index: Number
  }
}

Side note: it's recommended you key lists using a unique identifier (e.g: id) rather than based on their position in the list. For example, if any items get replaced or updated, Vue might not re-render, because the items' position in the array has not changed, even if the item itself has.

This is why list transitions don't work when you key items by index.

However, if your items don't change position and/or do not get updated, index as key does the job.

  • Related