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="{ 'active': index < currentRating }"
>
★
</span>
</div>
</template>
<script>
export default {
data() {
return {
stars: Array(5).fill(null),
currentRating: 0,
tempRating: 0
}
},
methods: {
setRating(rating) {
this.currentRating = rating
},
hoverRating(rating) {
this.tempRating = rating
},
resetRating() {
this.tempRating = this.currentRating
}
},
computed: {
activeRating() {
return this.tempRating || this.currentRating
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating .active {
color: gold;
}
</style>
进阶功能实现
支持半星评分
<template>
<div class="star-rating">
<div
v-for="(star, index) in stars"
:key="index"
@click="setRating(index + 0.5)"
@mouseover="hoverRating(index + 0.5)"
>
<span class="half-star" :class="{ 'active': index < currentRating - 0.5 }">★</span>
<span class="full-star" :class="{ 'active': index < currentRating }">★</span>
</div>
</div>
</template>
双向数据绑定
props: {
value: {
type: Number,
default: 0
}
},
watch: {
currentRating(val) {
this.$emit('input', val)
}
}
使用第三方库
对于更复杂的需求,可以考虑以下库:
vue-star-rating:提供丰富的配置选项rate-it:支持多种样式和交互方式v-rating:Material Design风格的评分组件
安装示例:
npm install vue-star-rating
使用示例:
<template>
<star-rating
v-model="rating"
:star-size="30"
:show-rating="false"
/>
</template>
<script>
import StarRating from 'vue-star-rating'
export default {
components: { StarRating },
data() {
return {
rating: 3
}
}
}
</script>
样式定制技巧
通过CSS变量实现主题色定制:
.star-rating {
--active-color: #ffd700;
--inactive-color: #ddd;
}
.star-rating span {
color: var(--inactive-color);
}
.star-rating .active {
color: var(--active-color);
}
添加动画效果:
.star-rating span {
transition: all 0.2s ease;
}
.star-rating span:hover {
transform: scale(1.2);
}
无障碍访问优化
增加ARIA属性:
<span
role="radio"
:aria-checked="index < currentRating"
:aria-label="`Rate ${index + 1} out of 5`"
>
★
</span>






