2

following some research across the web, i understand i should add index to the loop and then add it as a key. how would you suggest creating a unique key for both td's in the following code:

      <template v-for="lesson in lessons">
        <td @click="sort(lesson.questions)" :key="lesson.lessonId">
           questions
        </td>
        <td @click="sort(lesson.grade)" :key="lesson.lessonId">
           grade
        </td>
      </template>

the only idea i had was to add index to the loop and then have the second index as follows:

:key="`${lesson.lessonId}+1`"

but that feels a bit odd and error prone, am i right?

3 Answers 3

4

There are 2 ways,

first is add the static number as you mentioned:

:key="`${lesson.lessonId}567`"

Second is generate a new ID, and you will using uuid version 4 package, that will generate random id for you,

<template>
 :key="generateID"
</template>


<script>
const uuidv4 = require('uuid/v4');

module.exports = {
  data: function () {
    return {
      generateID: uuidv4();
    }
  }
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

The special attribute 'key' can be either 'numeric' or 'string', to solve the problem you can prefix your lessonId with a string

  <template v-for="lesson in lessons">
    <td @click="sort(lesson.questions)" :key="`question_${lesson.lessonId}`">
       questions
    </td>
    <td @click="sort(lesson.grade)" :key="`grade_${lesson.lessonId}`">
       grade
    </td>
  </template>`

Comments

0
<ul id="example-2">
  <li v-for="(item, index) in items" :key="key(index, item)">
    {{ parentMessage }} - {{ index }} - {{ item.message }}
  </li>
</ul>

var example2 = new Vue({
  el: '#example-2',
  data: {
    parentMessage: 'Parent',
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  },
  methods: {
    key (index, item) {
        return `${index}${item.message}`
    }
  }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.