how to add :key in v-for with multiple divs

Viewed 1171

I want to make v-for loop without any html element so I decided to use <template as parent. I don't know to assign :key for this loop. I can't assign it to template and to every div inside loop. Any ideas?

<template
  v-for="{ id, text, option, percentage, value } in reports"
>
  <div class="table-row__index">
    {{ id }}
  </div>
  <div class="table-row__title">
    <p>{{ text }} - <strong>{{ option }}</strong></p>
  </div>
  <div class="table-row__info">
    {{ percentage }}%
  </div>
  <div class="table-row__info">
    {{ value }}
  </div>
</template>
2 Answers

As a good practice we should always have a parent element inside. But due to your constraints, it's okay to use for loop on template as given in official docs

https://v2.vuejs.org/v2/guide/list.html#v-for-on-a-lt-template-gt

In this case, any keys have to be added to child elements/components and this is what officially recommended.

See this example and please add keys to your div's inside template.

new Vue({
    el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <template v-for="n in 5">
    <span :key="'number' + n">{{ n }}</span>
    <span :key="'dot' + n">. </span>
  </template>
</div>

you just can't have the for loop in your template. The for loop directive is only allowed to be inside the first child component ( or root component) inside your template.

Here is an example of how you can render your loop:

<template>
  <div class="cant-have-for-loop-this-is-the-root-component">
    <div v-for="{ id, text, option, percentage, value } in reports" :key="{id}">
        <div class="table-row__index">
          {{ id }}
        </div>
        <div class="table-row__title">
        <p> {{ text }} - <strong>{{ option }}</strong></p>
        </div>
        <div class="table-row__info">
            {{ percentage }}%
        </div>
        <div class="table-row__info">
            {{ value }}
        </div>
    </div>
  </div>
</template>

This runs soomthly, and with no hesitations. And renders with no styling as this screenshots depicts:

enter image description here

Hope this answers what you want to achieve.

Related