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

新手上路,请多包涵

我正在构建 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>

错误似乎来自 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>

如果有人可以提供帮助,那就太好了!?

原文由 Drostan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 689
2 个回答

您可以简单地避免在 :key 中使用 v-for

 ...
<div v-for="comment in comments">
...

正如 vuejs 文档 所说:

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

原文由 jotade 发布,翻译遵循 CC BY-SA 4.0 许可协议

其他答案有效,但以下也值得一试:

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

原文由 silvan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题