At any given time the code below displays five consecutive stars. These are either a star1.png (yellow) or a star0.png (black). When the user hovers over, say, the third star, the first three stars are to turn into star1.png (yellow), with the remaining two stars being star0.png (black).
The code works initially, with some [Vue warn]: Duplicate keys detected warnings when hovering over a star, until eventually hovering over a different star causes
[Vue warn]: Error in nextTick: "TypeError: Cannot read properties of undefined (reading 'key')"TypeError: Cannot read properties of undefined (reading 'key')
I’m not certain what is causing this, and would appreciate help in figuring it out.
<template>
<div class="col-sm border-right">
<span v-for="n in rating" :key="n">
<img src="../assets/star1.png" style="width: 6vh;" @mouseover="stars(n)">
</span>
<span v-for="m in 5-rating" :key="m">
<img src="../assets/star0.png" style="width: 6vh;" @mouseover="stars(m)">
</span>
</div>
</template>
<script>
export default {
data(){
return {
rating: 0
}
},
methods: {
stars(n){
this.rating = n;
},
}
}
</script>
>Solution :
Both of the keys your using (n and m) are the same.
The key attribute is used by vue.js to track each node’s identity and should be unique across all the nodes of the same parent.
Both v-for loops use numbers as keys, which leads to a conflict because the same number can appear in both loops.
<template>
<div class="col-sm border-right">
<!-- First loop for yellow stars -->
<span v-for="n in rating" :key="'filled-' + n">
<img src="../assets/star1.png" style="width: 6vh;" @mouseover="stars(n)">
</span>
<!-- Second loop for black stars -->
<span v-for="m in 5-rating" :key="'empty-' + m">
<img src="../assets/star0.png" style="width: 6vh;" @mouseover="stars(m)">
</span>
</div>
</template>
<script>
export default {
data(){
return {
rating: 0
}
},
methods: {
stars(n){
this.rating = n;
},
}
}
</script>