vue实现店铺星级评价
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 可设置为只读模式。

自定义 SVG 星级组件
创建可复用的 StarRating.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"/>




