vue实现点击星星评分

实现思路
通过Vue的数据绑定和事件处理机制,动态渲染星星图标并处理用户点击事件。使用v-for循环生成星星,根据当前评分高亮对应数量的星星。
代码实现
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="rate(star)"
:class="{ 'active': star <= currentStars }"
>
★
</span>
<p>当前评分: {{ currentStars }} / {{ maxStars }}</p>
</div>
</template>
<script>
export default {
data() {
return {
maxStars: 5,
currentStars: 0
}
},
methods: {
rate(star) {
this.currentStars = star
}
}
}
</script>
<style>
.star-rating span {
font-size: 30px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
功能扩展
- 添加半星评分功能
data() { return { maxStars: 5, currentStars: 0, tempStars: 0 } }, methods: { rate(star) { this.currentStars = star }, setTemp(star) { this.tempStars = star }, resetTemp() { this.tempStars = this.currentStars } }
<span
v-for="star in maxStars"
:key="star"
@click="rate(star)"
@mouseover="setTemp(star)"
@mouseout="resetTemp"
:class="{
'active': star <= currentStars,
'temp-active': star <= tempStars
}"
>
★
</span>
- 添加只读模式
<span v-for="star in maxStars" :key="star" :class="{ 'active': star <= currentStars }" v-if="readonly" > ★ </span>
使用组件
<star-rating v-model="ratingValue" :max-stars="10" readonly></star-rating>
注意事项
- 确保为星星元素添加合适的cursor样式以提示可点击
- 考虑添加过渡动画效果提升用户体验
- 对于移动端需要添加touch事件支持
- 可以通过props接收初始评分值







