vue实现星级评价
实现星级评价的基本思路
在Vue中实现星级评价功能,通常需要创建一个可交互的星级评分组件。用户可以通过点击或悬停来选择评分,组件需要展示当前评分并允许动态更新。
组件模板结构
使用v-for渲染星星图标,通过计算属性或方法动态控制星星的激活状态。以下是一个基础模板示例:
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="setRating(index + 1)"
@mouseover="hoverRating(index + 1)"
@mouseleave="resetRating"
:class="['star', { 'active': index < currentRating }]"
>
★
</span>
</div>
</template>
组件逻辑实现
定义数据属性和方法控制评分交互。需要维护当前评分(currentRating)和悬停时的临时评分(hoverRating)。
<script>
export default {
data() {
return {
stars: 5, // 总星数
currentRating: 0, // 当前选中评分
tempRating: 0 // 悬停时的临时评分
};
},
methods: {
setRating(rating) {
this.currentRating = rating;
this.$emit('rating-selected', rating); // 向父组件传递评分
},
hoverRating(rating) {
this.tempRating = rating;
},
resetRating() {
this.tempRating = 0;
}
},
computed: {
displayedRating() {
return this.tempRating || this.currentRating;
}
}
};
</script>
样式设计
通过CSS控制星星的样式和颜色变化。未激活的星星为灰色,激活的星星为金色或其他醒目颜色。
<style scoped>
.star-rating {
font-size: 24px;
}
.star {
color: #ccc;
cursor: pointer;
}
.star.active {
color: gold;
}
</style>
使用组件
在父组件中引入并使用星级评价组件,监听评分事件。
<template>
<div>
<star-rating @rating-selected="handleRating" />
<p>当前评分: {{ selectedRating }}</p>
</div>
</template>
<script>
import StarRating from './StarRating.vue';
export default {
components: {
StarRating
},
data() {
return {
selectedRating: 0
};
},
methods: {
handleRating(rating) {
this.selectedRating = rating;
}
}
};
</script>
高级功能扩展
- 半星评分:通过计算显示半颗星(如使用
☆和½符号)。 - 只读模式:通过
props禁用交互,仅用于展示评分。 - 自定义图标:使用
Font Awesome或自定义SVG替代★符号。
// 半星评分示例
computed: {
starClasses() {
return this.stars.map((_, index) => ({
'half': this.displayedRating - index === 0.5,
'active': index < Math.floor(this.displayedRating)
}));
}
}
注意事项
- 双向绑定:可以通过
v-model实现更灵活的数据绑定。 - 无障碍访问:为星星添加
aria-label和role属性,提升可访问性。 - 性能优化:大量渲染时考虑使用
v-show替代v-if。



