当前位置:首页 > VUE

vue实现店铺星级评价

2026-01-22 00:14:33VUE

Vue 实现店铺星级评价

使用组件库快速实现(如 Element UI)

安装 Element UI 后,可直接使用 el-rate 组件:

<template>
  <el-rate v-model="rating" :colors="colors" show-text></el-rate>
</template>

<script>
export default {
  data() {
    return {
      rating: 3.5,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900']
    }
  }
}
</script>

通过 allow-half 属性可启用半星评分,disabled 可设置为只读模式。

vue实现店铺星级评价

自定义 SVG 星级组件

创建可复用的 StarRating.vue 组件:

vue实现店铺星级评价

<template>
  <div class="star-rating">
    <span 
      v-for="(star, index) in stars" 
      :key="index"
      @click="setRating(index + 1)"
      @mouseover="hoverRating(index + 1)"
      @mouseleave="resetRating"
    >
      <svg :fill="star <= currentRating ? '#FFD700' : '#C0C0C0'">
        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
      </svg>
    </span>
  </div>
</template>

<script>
export default {
  props: {
    maxStars: { type: Number, default: 5 },
    initialRating: { type: Number, default: 0 }
  },
  data() {
    return {
      stars: Array(this.maxStars).fill().map((_, i) => i + 1),
      currentRating: this.initialRating,
      tempRating: 0
    }
  },
  methods: {
    setRating(rating) {
      this.currentRating = rating
      this.$emit('rating-selected', rating)
    },
    hoverRating(rating) {
      this.tempRating = this.currentRating
      this.currentRating = rating
    },
    resetRating() {
      this.currentRating = this.tempRating
    }
  }
}
</script>

<style>
.star-rating svg {
  width: 24px;
  height: 24px;
  cursor: pointer;
}
</style>

实现半星评分

修改自定义组件的 SVG 渲染逻辑:

// 在模板中替换为两个半星路径
<svg v-if="showHalfStar(index)" viewBox="0 0 24 24">
  <path d="M12 2L9.19 8.63L2 9.24L7.46 14.47L5.82 21L12 17.27V2Z" fill="#FFD700"/>
  <path d="M12 2V17.27L18.18 21L16.54 14.47L22 9.24L14.81 8.63L12 2Z" fill="#C0C0C0"/>
</svg>

methods: {
  showHalfStar(index) {
    const decimal = this.currentRating - Math.floor(this.currentRating)
    return decimal > 0 && index === Math.floor(this.currentRating)
  }
}

动态评分显示

结合后端数据展示实际评分:

// 在父组件中
async fetchShopRating() {
  const res = await axios.get('/api/shop/rating')
  this.shopRating = res.data.average_rating
}

// 模板中使用
<star-rating :initial-rating="shopRating" :readonly="true"/>

标签: 星级店铺
分享给朋友:

相关文章

vue实现店铺分享

vue实现店铺分享

Vue实现店铺分享功能 使用Vue的社交分享组件 安装vue-social-sharing库,该库提供多种社交平台的分享功能。通过npm安装: npm install vue-social-sha…

vue实现星级评分

vue实现星级评分

实现星级评分的基本思路 在Vue中实现星级评分通常需要创建一个可交互的组件,允许用户点击或悬停选择评分。核心逻辑包括渲染星星图标、处理用户交互以及动态更新评分状态。 使用Font Awesome图标…

vue 实现星级评价

vue 实现星级评价

实现星级评价的步骤 使用组件实现星级评价 在Vue中,可以通过创建一个星级评价组件来实现。该组件允许用户点击星星进行评分,并显示当前评分。 <template> <div c…

vue实现星级评分效果

vue实现星级评分效果

实现星级评分的基础结构 使用Vue实现星级评分需要构建一个可交互的星级组件。基本思路是通过v-for循环生成星星图标,并通过动态绑定类名或样式来控制选中状态。 <template>…