获取错误“ index.vue中的迭代元素期望具有'v-bind:key'指令vue / require-v-for-key“

时间:2019-01-17 02:58:54

标签: vue.js contentful

我是vue.js的新手。我有一个简单的index.vue,它试图连接到内容丰富的目录并显示内容丰富的条目。我在index.vue中的代码如下:


<template>
  <div>
    <!-- render data of the person -->
    <h1>{{ person.fields.name }}</h1>
    <!-- render blog posts -->
    <ul>
      <li v-for="post in posts">
        {{ post.fields.title }}
      </li>
    </ul>
  </div>
</template>

<script>
  import {createClient} from '~/plugins/contentful.js'

  const client = createClient()

但是,当我从浏览器尝试localhost:3000时,它返回以下错误:


./pages/index.vue中的

错误 模块错误(来自./node_modules/eslint-loader/index.js):

C:\ Users \ admin \ pdress \ pages \ index.vue   7:7错误迭代中的元素期望具有'v-bind:key'指令vue / require-v-for-key

✖1个问题(1个错误,0个警告)


如果有人可以帮助我进一步学习vue.js,我将不胜感激。预先感谢

3 个答案:

答案 0 :(得分:1)

<template>
  <div>
    <!-- render data of the person -->
    <h1>{{ person.fields.name }}</h1>
    <!-- render blog posts -->
    <ul>
      <li v-for="post in posts" :key = "post">
        {{ post.fields.title }}
      </li>
    </ul>
  </div>
</template>


If this is not going to work use any unique field from your object for example if you have id in your object then,
:key = "post.id"

答案 1 :(得分:0)

@ljubadr的建议是正确的。您需要这样做:

<li v-for="post in posts" v-bind:key="post.id">

<!-- OR USE SHORTCUT NOTATION -->
<li v-for="post in posts" :key="post.id">

原因与性能有关。属性key可帮助Vue确定列表中的唯一项。考虑排序的例子。如果您的用户界面有一个用于发布的排序按钮,那么您在post数组中的项目顺序将发生变化。但这是否意味着Vue将重新渲染整个列表?当然不是!使用:key可以确定该项是否已经在UI上呈现。它只是简单地对DOM节点进行改组并节省了昂贵的渲染周期。

第二,如果在使用v-for时列表中包含复杂的组件,而未提供:key,则只要更改或重新排序列表,它只会更改DOM,但不会不会破坏现有组件,并且可能导致局部状态不匹配。这就是为什么必须具有:key属性的原因。

Read Vue.js documentation,以获取更多信息。

注意:还请记住,将v-for的{​​{1}} index用于:key是个坏主意,因为它在整个收藏集中并不是唯一的。

答案 2 :(得分:0)

您必须为

定义:键属性

v-for指令。还有<transition-group>标签。

在这种情况下,v-for您必须显式设置

  <li v-for="(post, i) in posts" :key="i + 10">
    {{ post.fields.title }}
  </li>

如果您注意到可以在v-for中定义最多两个参数,则必须定义项目(帖子)并可以定义帖子的索引。