[Vue警告]:避免将非原始值用作键,而应使用字符串/数字值

joh*_*ybo 9 javascript vue.js

我正在构建一个HackerNews的克隆,并收到以下错误:

vue.esm.js?efeb:591 [Vue warn]: Avoid using non-primitive value as key, use string/number value instead.

found in

---> <Single> at src/components/Single.vue
       <App> at src/App.vue
         <Root>
Run Code Online (Sandbox Code Playgroud)

该错误似乎来自Single.vue,但我无法正常工作?模板如下:

<template>
    <div class="container">
        <h2>{{ story.title }}</h2>
        <p>Score: {{ story.score }}</p>
        <p>{{ story.url }}</p>
        <div v-for="comment in comments" :key="comment">
          <div class="comment-wrap">
                <div class="comment-block">
                    <p class="comment-text">{{ comment.text }}</p>
                    <div class="bottom-comment">
                        <div class="comment-author">{{ comment.by }}</div>
                        <div class="comment-date">{{ comment.time }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助您,那就太好了!

Wil*_*ong 14

警告从源<div v-for="comment in comments" :key="comment">,其中,所述对象comment被用作keyv-for。警告的含义很直白,请勿使用Object作为键。

使用唯一的原始值作为键,也许像comment.id${comment.time}${comment.by}

  • 这句话其实是有道理的。 (2认同)

小智 11

其他答案也可以,但是以下方法也值得一试:

<div v-for="(comment, idx) in comments" :key="idx">
  <!-- ... -->
</div>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这很完美 (5认同)

小智 9

你可以简单地避免使用:key在你的v-for

...
<div v-for="comment in comments">
...
Run Code Online (Sandbox Code Playgroud)

正如vuejs 文档所说:

建议尽可能使用v-for提供密钥,除非迭代的DOM内容很简单,或者您有意依赖默认行为来获得性能。

  • 这是可行的,但是会导致IDE警告“迭代中的元素期望具有v-bind:key指示符” (4认同)

小智 8

下面是一个对我有用的例子。希望有帮助

在此处输入图片说明

  • 不建议如此处解释/sf/ask/3117205731/ (4认同)

Vis*_*iya 8

使用唯一的原始值作为键,建议尽可能提供一个key属性v-for

喜欢 :key="design.uniqueId"

<li v-for="design in designs" :key="design.id">
    <!-- code -->
</li>

<li v-for="loop in loops" :key="loop.id">
    <!-- code -->
</li>
Run Code Online (Sandbox Code Playgroud)

比如Vue.js 文档