Error screenshot:
Reason for error:
From the error message in the above figure, it is not difficult to see that the main reason for the error is key
the value . The error probably means that a duplicate key
value was detected. Generally speaking, your key
value is not unique.
solution:
Once the root of the problem is found, the solution will be very concise. In fact, this kind of error occurs in the project mostly in the following two situations:
First case:
for
key
The value of the loop is not unique.
<template>
<div>
<div v-for="(item,index) in listData" :key="item.idx">{
{
item.name}}</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [
{
idx: "0", name: "数据1" },
{
idx: "0", name: "数据2" },
{
idx: "1", name: "数据3" },
],
};
},
};
</script>
Second case:
There are two for
loops , resulting in key
duplicates.
<template>
<div>
<div v-for="(item,index) in listData" :key="item.idx">{
{
item.name}}</div>
<div v-for="(item,index) in listData" :key="item.idx">{
{
item.name}}</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [
{
idx: "0", name: "数据1" },
{
idx: "1", name: "数据2" },
{
idx: "2", name: "数据3" },
],
};
},
};
</script>
The above are two common situations that cause errors. The following will teach you how to solve this problem.
<template>
<div>
<div v-for="(item,index) in listData" :key="index">{
{
item.name}}</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [
{
idx: "0", name: "数据1" },
{
idx: "0", name: "数据2" },
{
idx: "1", name: "数据3" },
],
};
},
};
</script>
In the first case, we can directly specify key
the value as the valuefor
of the cycle , which can solve the problem of repetition.index
key
<template>
<div>
<div v-for="(item,index) in listData" :key="item.idx + 1">{
{
item.name}}</div>
<div v-for="(item,index) in listData" :key="item.idx">{
{
item.name}}</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [
{
idx: "0", name: "数据1" },
{
idx: "1", name: "数据2" },
{
idx: "2", name: "数据3" },
],
};
},
};
</script>
In the second case, we can see that we spliced the value in the first for
loop with a number, so that the values in the two loops are unique, so no error will be reported. In fact, not only numbers, strings or other marks can be distinguished and are worth uniqueness. Interested students can go down and give it a try.key
for
key
key