vue实现评分星星
Vue 实现评分星星组件
使用 Vue 实现评分星星功能可以通过自定义组件完成,以下是两种常见实现方式:
基础实现(静态评分)
<template>
<div class="star-rating">
<span
v-for="star in 5"
:key="star"
@click="setRating(star)"
:class="{ 'active': star <= currentRating }"
>★</span>
</div>
</template>
<script>
export default {
data() {
return {
currentRating: 0
}
},
methods: {
setRating(rating) {
this.currentRating = rating
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
进阶实现(支持半星评分)
<template>
<div class="star-rating">
<div
v-for="star in 5"
:key="star"
class="star-container"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
@click="setRating(star)"
>
<div class="star-background">★</div>
<div
class="star-foreground"
:style="{ width: getStarWidth(star) }"
>★</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentRating: 0,
hoverRating: 0
}
},
methods: {
setRating(rating) {
this.currentRating = rating
},
getStarWidth(star) {
const displayRating = this.hoverRating || this.currentRating
return star <= displayRating ? '100%' :
star - 0.5 <= displayRating ? '50%' : '0%'
}
}
}
</script>
<style>
.star-rating {
display: flex;
}
.star-container {
position: relative;
font-size: 24px;
cursor: pointer;
}
.star-background {
color: #ccc;
}
.star-foreground {
position: absolute;
top: 0;
left: 0;
width: 0;
color: gold;
overflow: hidden;
white-space: nowrap;
}
</style>
使用第三方库
对于更复杂的需求,可以考虑使用现成的评分组件库:
-
安装
vue-star-rating:npm install vue-star-rating -
使用示例:
<template> <star-rating v-model="rating" :increment="0.5" :star-size="20" /> </template>
export default { components: { StarRating }, data() { return { rating: 3.5 } } }
```注意事项
- 自定义组件时应考虑添加
v-model支持以实现双向绑定 - 可以添加
readonly属性支持只读模式 - 考虑添加动画效果提升用户体验
- 移动端需要添加触摸事件支持



