当前位置:首页 > 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中实现星级评价功能,通常需要创建一个可交互的星级评分组件。用户可以通过点击或悬停来选择评分,组件需要展示当前评分并允许动态更新。 组件模板结构 使用v-for渲染星星…

vue实现星级评分

vue实现星级评分

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

react实现星级评分

react实现星级评分

实现星级评分的基本思路 使用React实现星级评分通常涉及状态管理、事件处理和动态渲染。核心逻辑包括跟踪当前评分和悬停状态,通过图标或文字展示星级。 使用状态管理评分 创建组件并初始化状态,存储当前…

css制作店铺

css制作店铺

CSS制作店铺的基本方法 创建一个店铺页面需要结合HTML结构和CSS样式。以下是一些关键步骤: HTML结构设计 使用语义化标签构建店铺框架,例如<header>、<nav>…

js实现星级

js实现星级

实现星级评分的基本方法 使用HTML和CSS创建星级评分的界面结构。通常用<div>或<span>元素表示星星,并通过CSS设置样式。 <div class="star…