🖥

Vue の v-for で bind しなさいと Lint に怒られるのだが何がいけないのか... (Elements in iterati

に公開

Lintのエラーで 怒られるが、よく後ろを見ると、表示自体はちゃんと出来ているのが分かる

image

data

dataがこういう時

  data () {
    return {
      posts: [
        { id: 1, title: 'My journey with Vue' },
        { id: 2, title: 'Blogging with Vue' },
        { id: 3, title: 'Why Vue is so fun' }
      ]
    }

NG

<li v-for="post in posts">
  {{ post.title }}
</li>

OK

<li v-for="post in posts" :key="post.id">
  {{ post.title }}
</li>

OK ...?

bindの値は 特に v-for の中で表示に使われるわけではないらしい
存在しないキーを指定しても動作して、lintでは怒られなくなった ( null 的な扱いになっているかも )

<li v-for="post in posts" :key="post.xxx">
  {{ post.title }}
</li>

何故か

表示だけの場合はまず bind 指定なしでも問題ないが、削除したりする時に、要素を一意に特定するためのもの、とかだろうか

【徹底解説】これを見ればわかるvue.jsのv-forのkeyの動作 | アールエフェクト

Code

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <ul>
      <li v-for="post in posts">
        {{ post.id }} {{ post.title }}
      </li>
    </ul>
  </div>
</template>

<script>

export default {
  name: 'App',
  data () {
    return {
      posts: [
        { id: 1, title: 'My journey with Vue' },
        { id: 2, title: 'Blogging with Vue' },
        { id: 3, title: 'Why Vue is so fun' }
      ]
    }
  }
}
</script>

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3101

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-04-30

Discussion