vue实现店铺星级评价
实现思路
在Vue中实现店铺星级评价功能,可以通过组件化方式构建一个可交互的星级评分系统。核心逻辑包括:渲染星级图标、处理用户点击或悬停事件、动态计算评分值。
基础组件结构
创建一个StarRating.vue组件,包含模板、脚本和样式部分。使用v-for循环渲染5颗星,通过动态类名控制星级的选中状态。

<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="rate(index + 1)"
@mouseover="hover(index + 1)"
@mouseleave="resetRating"
:class="['star', { 'filled': (hoverRating || currentRating) >= index + 1 }]"
>
★
</span>
<p v-if="showScore">当前评分: {{ currentRating }}</p>
</div>
</template>
核心逻辑实现
脚本部分定义评分数据和方法,使用v-model实现双向绑定以便父组件获取评分值。
<script>
export default {
props: {
value: { type: Number, default: 0 },
showScore: { type: Boolean, default: true }
},
data() {
return {
stars: [1, 2, 3, 4, 5],
currentRating: this.value,
hoverRating: 0
}
},
methods: {
rate(score) {
this.currentRating = score;
this.$emit('input', score);
},
hover(score) {
this.hoverRating = score;
},
resetRating() {
this.hoverRating = 0;
}
},
watch: {
value(newVal) {
this.currentRating = newVal;
}
}
}
</script>
样式优化
添加CSS样式增强视觉效果,包括默认星形和选中状态的样式差异。

<style scoped>
.star-rating {
font-size: 24px;
cursor: pointer;
}
.star {
color: #ccc;
transition: color 0.2s;
}
.filled {
color: #ffcc00;
}
</style>
使用示例
在父组件中引入并使用星级评分组件,可通过v-model绑定评分数据。
<template>
<div>
<star-rating v-model="rating"></star-rating>
<p>提交的评分: {{ rating }}</p>
</div>
</template>
<script>
import StarRating from './StarRating.vue';
export default {
components: { StarRating },
data() {
return {
rating: 3
}
}
}
</script>
高级功能扩展
支持半星评分需要修改渲染逻辑和样式。使用字体图标或SVG替代Unicode字符会更灵活。
// 在data中定义半星状态
halfStars: [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
<!-- 修改模板部分 -->
<span
v-for="(star, index) in halfStars"
:key="index"
@click="rate(star)"
:class="['star', { 'filled': currentRating >= star }]"
>
{{ star % 1 === 0 ? '★' : '½' }}
</span>
注意事项
确保组件在不同屏幕尺寸下的显示一致性,可以通过响应式单位如em或rem设置字体大小。对于无障碍访问,应添加aria-label等属性。





