vue评分实现
实现 Vue 评分组件的基本思路
使用 Vue 实现评分功能通常需要以下核心逻辑:通过数据绑定动态渲染星星图标,根据用户交互(点击或悬停)更新评分状态,并支持自定义样式和功能。
基础实现方案
模板部分
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="rate(index + 1)"
@mouseover="hover(index + 1)"
@mouseleave="resetHover"
:class="['star', { 'filled': (hoverRating || currentRating) >= index + 1 }]"
>★</span>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
stars: Array(5).fill(null), // 5颗星
currentRating: 0, // 当前评分
hoverRating: 0 // 悬停时的临时评分
};
},
methods: {
rate(score) {
this.currentRating = score;
},
hover(score) {
this.hoverRating = score;
},
resetHover() {
this.hoverRating = 0;
}
}
};
</script>
样式部分
<style>
.star-rating {
font-size: 24px;
}
.star {
color: #ccc;
cursor: pointer;
}
.filled {
color: gold;
}
</style>
进阶功能扩展
支持半星评分 修改模板和逻辑,通过计算样式类名实现半星效果:
<span
v-for="(star, index) in stars"
:class="[
'star',
{ 'half-filled': (hoverRating || currentRating) >= index + 0.5 },
{ 'filled': (hoverRating || currentRating) >= index + 1 }
]"
>
★
</span>
添加 props 参数 使组件可配置化:
props: {
maxRating: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
}
}
事件触发 在评分变化时触发事件:
methods: {
rate(score) {
this.currentRating = score;
this.$emit('rated', score);
}
}
第三方库方案
对于更复杂的需求,可以考虑以下流行库:
- vue-star-rating: 提供丰富的配置选项和动画效果
- rate-it: 轻量级解决方案,支持触摸事件
- element-ui/element-plus: 内置评分组件(ElRate)
安装示例(以vue-star-rating为例):
npm install vue-star-rating
使用方式:
import StarRating from 'vue-star-rating';
export default {
components: {
StarRating
}
}
<star-rating
:rating="3.5"
:increment="0.5"
:max-rating="5"
@rating-selected="setRating"
></star-rating>
移动端适配要点
- 添加触摸事件支持(@touchstart等)
- 适当增大点击区域
- 考虑使用 SVG 替代 Unicode 字符以获得更好显示效果
- 添加过渡动画提升用户体验
通过以上方法可以实现从简单到复杂的评分功能,根据项目需求选择合适方案。







