Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of ESLint error <template v-for> key should be placed on the <template> tag?

I am using NuxtJS with Vuetify in an app. When showing a table of records with v-data-table, I want to show a badge if the item.isActive is true. For that, I am looping over <template> inside <tr>. Whenever I am providing key to the <template> tag I am getting '<template v-for>' cannot be keyed. Place the key on real elements instead. When I am trying to key the <td>, I am getting <template v-for> key should be placed on the <template> tag. This is faced in VSCode with ESLint

1st Error

enter image description here

2nd Error

enter image description here

Implementation:

  <v-data-table :items="items">
    <template v-slot:item="{ item }">
      <tr>
        <template v-for="(header, index) in headers">
          <td v-if="header.value === 'isActive'" :key="index">
            <v-badge bordered content="" offset-x="-10" color="'#64b54d'" />
          </td>
          <td
            v-else
            :key="index"
          >
            {{ item[header.value] }}
          </td>
        </template>
      </tr>
    </template>
  </v-data-table>

CodeSandbox link: https://codesandbox.io/s/runtime-wood-q4mc5h?file=/pages/home.vue:11-585

Thanks in Advance.


1 Answers

I've had similar situations and for me, this is what it boils down to (although the error does not say that specifically):

There is no reason to use a <template> tag in that situation. Putting v-for on the child inside the <template> would give you the exact same output.

Here are some screenshots to clarify:

  1. Here we have an error.

Here we have an error

  1. Adding a v-if on the child could for example be a reason for using <template> (v-if should not be used on the same element as v-for). Now the error is gone.

No error anymore

  1. Or we simply loop the element inside the <template> tag and the error goes away.

No error anymore

like image 94
Leopold Kristjansson Avatar answered Sep 07 '25 20:09

Leopold Kristjansson