Avoid using non-primitive value as key, use string/number value instead. 怎么解决
时间: 2024-03-08 20:49:38 浏览: 30
这个警告是由 Vue 的 key 绑定机制引起的,当你给一个非原始值(如对象或数组)分配 key 值时,Vue 会发出这个警告。这是因为非原始值无法被有效比较,可能导致性能问题或意外行为。
要解决这个问题,你可以将非原始值转换为字符串或数字,以便 Vue 可以正确比较 key 值。以下是一些解决方法:
1. 使用字符串或数字作为 key
如果你的数据是对象数组,可以使用对象属性的值作为 key,如下所示:
```html
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
```
在这个例子中,我们使用 item.id 作为 key 值,因为它是一个数字。
2. 使用计算属性
你可以使用计算属性将非原始值转换为字符串或数字,然后将其用作 key 值。例如:
```html
<template>
<div>
<ul>
<li v-for="item in computedItems" :key="item.key">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'item 1' },
{ id: 2, name: 'item 2' },
{ id: 3, name: 'item 3' },
],
};
},
computed: {
computedItems() {
return this.items.map((item) => {
return {
key: String(item.id),
name: item.name,
};
});
},
},
};
</script>
```
在这个例子中,我们定义了一个计算属性 computedItems,该属性将 items 数组转换为包含 key 和 name 属性的新数组。key 属性被转换为字符串,因此我们可以安全地将其用作 key 值。
3. 使用 Vue 的内置 key
Vue 还提供了一个特殊的内置 key 值 $index,它可以用于遍历简单数组,例如:
```html
<template>
<div>
<ul>
<li v-for="(item, index) in items" :key="$index">{{ item }}</li>
</ul>
</div>
</template>
```
在这个例子中,我们使用 $index 作为 key 值,因为它是一个数字,且在遍历简单数组时是有效的。
总之,为了避免这个警告,你需要确保将非原始值转换为字符串或数字,并将其用作 key 值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)