Javascript [Vue warn]:避免使用非原语值作为键,而是使用字符串/数字值
我正在构建HackerNews的克隆,出现以下错误:Javascript [Vue warn]:避免使用非原语值作为键,而是使用字符串/数字值,javascript,vue.js,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>
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>
vue.esm.js?efeb:591[vue warn]:避免使用非原语值作为键,而是使用字符串/数字值。
发现于
--->在src/components/Single.vue处
在src/App.vue
错误似乎来自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>
{{story.title}
分数:{{story.Score}
{{story.url}
{{comment.text}
{{comment.by}}
{{comment.time}
如果有人能帮忙,那就太好了 来自
的警告源,其中对象注释
用作的键
。警告的含义是相当字面的,不要使用对象作为键
使用唯一原语值作为键,可能类似于comment.id
或${comment.time}${comment.by}
您可以简单地避免在v-for
中使用:key
...
<div v-for="comment in comments">
...
。。。
...
正如vuejs所说:
建议尽可能提供带v-for的钥匙,除非
迭代的DOM内容很简单,或者您有意依赖
性能增益的默认行为
其他答案也行,但以下也值得一试:
下面是一个对我有效的例子。希望有帮助
使用唯一原语值作为键,
建议尽可能为key
属性提供v-for
比如:key=“design.uniqueId”
例如可能您正在使用对象类型作为键,如果可以将其转换为唯一的字符串,请通过调用例如
toString来使用该字符串而不是实例
当我使用mongoose.Types.ObjectId()
作为键时,在我更改为mongoose.Types.ObjectId().toHexString()
后,警告消失。根据vue js文档,您的id被多次查找
这意味着您的代码应该如下所示
div v-for=“评论中的评论”:key=“comment.id”>
代替
div v-for=“评论中的评论”:key=“评论”>
要给Vue一个提示,使其能够跟踪每个节点的标识,从而重用和重新排序现有元素,您需要为每个项目提供一个唯一的键属性这是可行的,但它会导致IDE警告“迭代中的元素预期具有v-bind:键派生”,建议遵循指导原则。为什么不使用计算属性以字符串格式返回注释key=“getComents(comment)”。这是可行的。谢谢。这是perfectIndex,只有在您确定数组内容是不可变的情况下,才应该将其用作键。不推荐使用。正如本文所解释的,这一点实际上是有意义的。
<li v-for="design in designs" :key="design.id">
<!-- code -->
</li>
<li v-for="loop in loops" :key="loop.id">
<!-- code -->
</li>