在 Vue 中实现简短的五星级评级系统

问题描述 投票:0回答:1

在任何给定时间,下面的代码都会显示五个连续的星星。这些是

star1.png
(黄色)或
star0.png
(黑色)。当用户将鼠标悬停在第三颗星星上时,前三颗星星将变成
star1.png
(黄色),其余两颗星星变为
star0.png
(黑色)。

该代码最初有效,当悬停在一颗星星上时会出现一些

[Vue warn]: Duplicate keys detected
警告,直到最终悬停在另一颗星星上时导致

  • [Vue warn]: Error in nextTick: "TypeError: Cannot read properties of undefined (reading 'key')"
  • TypeError: Cannot read properties of undefined (reading 'key')

我不确定是什么原因造成的,希望能帮助您解决问题。

<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>
javascript vuejs2
1个回答
2
投票

您使用的两个键(

n
m
)是相同的。 vue.js 使用 key 属性来跟踪每个节点的身份,并且在同一父节点的所有节点中应该是唯一的。 两个
v-for
循环都使用数字作为键,这会导致冲突,因为相同的数字可以出现在两个循环中。

<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>
© www.soinside.com 2019 - 2024. All rights reserved.