1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【瞬時に解決】vue.jsのエラー:Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key

Last updated at Posted at 2020-03-14

vue cliを使用してプロジェクトを作成していると、このようなエラーに遭遇するかもしれません。

Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key

対処法は意外にも簡単でした。
vue.jsの公式ドキュメントにも解決策が載っています。

たとえばv-forを使って、monkeyの名前をliタグの中に出したいとしましょう。

<template>
    <ul>
        <li v-for="monkey in monkeys">{{ monkey }}</li>
    </ul>
</template>

<script>

export default {
  data() {
    return {
      monkeys: ['Taro', 'Hanako', 'Jiro']
    }
  }
}
</script>

こう書くとエラーが発生してしまいアウトプットされません。

ところが以下のようにv-bind:key="monkey"liタグのなかに追加するとエラーが消えます:point_down:

解決!

<template>
    <ul>
        <li v-for="(monkey, dog) in monkeys" v-bind:key="dog">{{ monkey }}</li>
    </ul>
</template>

どうやらv-forを使うときは、v-bind:key=""を付け加えてあげる必要があるそうです。これはvue.jsの公式ドキュメントでも推奨されています。
v-bind:key=""の中身は、inの手前にくるもの(この場合は(monkey, dog))とそろえる必要があります。ただし、最初のオブジェクトとかぶるのはNGのようで、他とかぶらない名前を(monkey, dog このようにしてオブジェクトのあとにカンマで区切って付け加えるといいようです。ここではdogという名前をつけました。括弧にくくらないと、またエラーが出てしまいます。たとえば以下のようでは効きません。

誤り:heavy_multiplication_x:

<template>
    <ul>
        <li v-for="monkey,dog in monkeys" v-bind:key="dog">{{ monkey }}</li>
    </ul>
</template>

//以下も効きません。 

<template>
    <ul>
        <li v-for="monkey in monkeys" v-bind:key="dog">{{ monkey }}</li>
    </ul>
</template>

👆ご注意ください。

このようにして解決することができました!

とはいえ初心者なので、もし何かあればご指摘ください:speaking_head:

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?