当前位置:首页 > VUE

vue实现星星评分

2026-01-08 14:48:07VUE

vue实现星星评分的方法

使用组件实现星星评分

创建一个可复用的星星评分组件,通过v-for循环渲染星星图标,利用动态绑定类名实现选中和未选中状态。

<template>
  <div class="star-rating">
    <span 
      v-for="star in maxStars" 
      :key="star" 
      @click="rate(star)"
      :class="{ 'active': star <= stars }"
    >
      ★
    </span>
  </div>
</template>

<script>
export default {
  props: {
    maxStars: {
      type: Number,
      default: 5
    },
    initialRating: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      stars: this.initialRating
    }
  },
  methods: {
    rate(star) {
      this.stars = star
      this.$emit('rated', star)
    }
  }
}
</script>

<style>
.star-rating span {
  font-size: 24px;
  color: #ccc;
  cursor: pointer;
}
.star-rating span.active {
  color: gold;
}
</style>

使用第三方库

安装并使用专门的评分组件库,如vue-star-rating。

npm install vue-star-rating
<template>
  <star-rating 
    v-model="rating"
    :increment="0.5"
    :star-size="30"
  />
</template>

<script>
import StarRating from 'vue-star-rating'

export default {
  components: {
    StarRating
  },
  data() {
    return {
      rating: 3.5
    }
  }
}
</script>

实现半星评分

通过计算显示半星或全星,使用字体图标或SVG实现更精细的控制。

<template>
  <div class="star-rating">
    <span 
      v-for="star in starsArray" 
      :key="star.index"
      @click="rate(star.value)"
    >
      <span v-if="star.isHalf">½</span>
      <span v-else>★</span>
    </span>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 0
    },
    maxStars: {
      type: Number,
      default: 5
    }
  },
  computed: {
    starsArray() {
      const stars = []
      for (let i = 1; i <= this.maxStars; i++) {
        stars.push({
          index: i,
          value: i,
          isHalf: this.value >= i - 0.5 && this.value < i
        })
      }
      return stars
    }
  },
  methods: {
    rate(star) {
      this.$emit('input', star)
    }
  }
}
</script>

注意事项

  • 考虑添加hover效果提升用户体验
  • 支持禁用状态时移除点击事件
  • 可通过props控制星星大小、颜色和数量
  • 使用Font Awesome或其他图标库替代unicode字符会更美观

以上方法提供了从基础到高级的星星评分实现方案,可根据项目需求选择合适的实现方式。组件化方案便于复用,而第三方库则能快速实现复杂功能。

vue实现星星评分

标签: 评分星星
分享给朋友:

相关文章

vue 实现评分

vue 实现评分

Vue 实现评分功能 在 Vue 中实现评分功能可以通过多种方式完成,包括使用第三方组件库或自定义实现。以下是两种常见的方法: 使用第三方组件库(如 Element UI) Element UI 提…

vue实现评分

vue实现评分

Vue 实现评分功能 使用组件库实现 安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。 以 element-ui 为例: <temp…