vue实现打星
Vue 实现打星评分功能
基础实现思路
使用v-for循环生成星星图标,通过动态绑定class或样式实现选中效果。核心逻辑是通过点击或鼠标悬停事件改变当前选中的星数。
代码示例
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
:class="{
'active': star <= (hoverRating || currentRating),
'inactive': star > (hoverRating || currentRating)
}"
>★</span>
</div>
</template>
<script>
export default {
data() {
return {
maxStars: 5,
currentRating: 0,
hoverRating: 0
}
},
methods: {
setRating(star) {
this.currentRating = star
this.$emit('rating-changed', star)
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
cursor: pointer;
}
.active {
color: gold;
}
.inactive {
color: #ccc;
}
</style>
组件化封装
将评分组件独立封装,通过props接收配置参数:

props: {
maxStars: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
},
disabled: {
type: Boolean,
default: false
}
}
进阶功能实现
支持半星评分需要更复杂的逻辑处理:

// 计算实际显示的星数
displayRating(rating) {
return Math.round(rating * 2) / 2
}
使用第三方库
推荐使用专门为Vue设计的评分组件库:
- vue-star-rating
- vue-rate
安装后直接引入使用:
import VueStarRating from 'vue-star-rating'
export default { components: { VueStarRating } }
#### 注意事项
- 移动端需要考虑触摸事件
- 可访问性需要添加ARIA标签
- 双向绑定建议使用v-model实现
- 大型项目建议将样式抽离为SCSS变量






