当前位置:首页 > VUE

vue实现评分星星

2026-01-18 04:24:37VUE

Vue 实现评分星星组件

使用 Vue 实现评分星星功能可以通过自定义组件完成,以下是两种常见实现方式:

基础实现(静态评分)

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

<script>
export default {
  data() {
    return {
      currentRating: 0
    }
  },
  methods: {
    setRating(rating) {
      this.currentRating = rating
    }
  }
}
</script>

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

进阶实现(支持半星评分)

<template>
  <div class="star-rating">
    <div 
      v-for="star in 5"
      :key="star"
      class="star-container"
      @mouseover="hoverRating = star"
      @mouseleave="hoverRating = 0"
      @click="setRating(star)"
    >
      <div class="star-background">★</div>
      <div 
        class="star-foreground"
        :style="{ width: getStarWidth(star) }"
      >★</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentRating: 0,
      hoverRating: 0
    }
  },
  methods: {
    setRating(rating) {
      this.currentRating = rating
    },
    getStarWidth(star) {
      const displayRating = this.hoverRating || this.currentRating
      return star <= displayRating ? '100%' : 
             star - 0.5 <= displayRating ? '50%' : '0%'
    }
  }
}
</script>

<style>
.star-rating {
  display: flex;
}
.star-container {
  position: relative;
  font-size: 24px;
  cursor: pointer;
}
.star-background {
  color: #ccc;
}
.star-foreground {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  color: gold;
  overflow: hidden;
  white-space: nowrap;
}
</style>

使用第三方库

对于更复杂的需求,可以考虑使用现成的评分组件库:

  1. 安装 vue-star-rating

    npm install vue-star-rating
  2. 使用示例:

    
    <template>
    <star-rating 
     v-model="rating"
     :increment="0.5"
     :star-size="20"
    />
    </template>
import StarRating from 'vue-star-rating'

export default { components: { StarRating }, data() { return { rating: 3.5 } } }

```

注意事项

  • 自定义组件时应考虑添加 v-model 支持以实现双向绑定
  • 可以添加 readonly 属性支持只读模式
  • 考虑添加动画效果提升用户体验
  • 移动端需要添加触摸事件支持

vue实现评分星星

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

相关文章

vue实现星星评分

vue实现星星评分

Vue 实现星星评分 在 Vue 中实现星星评分功能,可以通过自定义组件或使用第三方库来完成。以下是两种常见实现方式: 自定义星星评分组件 创建一个可复用的星星评分组件,支持点击和悬停交互:…

vue滑动评分实现

vue滑动评分实现

Vue 滑动评分实现 使用原生 HTML5 range 输入 在 Vue 中可以通过 <input type="range"> 快速实现滑动评分功能。这种方法不需要额外依赖库,适合简单场景…