vue实现星级评分
Vue 实现星级评分的方法
使用组件库实现
安装 element-ui 或 ant-design-vue 等 UI 库,它们提供了现成的星级评分组件。
// 使用 element-ui 的 Rate 组件
<template>
<el-rate v-model="rating" :colors="colors"></el-rate>
</template>
<script>
export default {
data() {
return {
rating: 3,
colors: ['#99A9BF', '#F7BA2A', '#FF9900']
}
}
}
</script>
自定义实现
通过 Vue 的模板和事件绑定,可以自定义星级评分组件。

<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="rate(star)"
:class="{ 'active': star <= currentStars }"
>★</span>
</div>
</template>
<script>
export default {
props: {
maxStars: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
}
},
data() {
return {
currentStars: this.initialRating
}
},
methods: {
rate(star) {
this.currentStars = star
this.$emit('rated', star)
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
支持半星评分
如果需要支持半星评分,可以稍微修改逻辑和样式。

<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="rate(star)"
@mousemove="hover(star)"
@mouseleave="resetHover"
:class="getClass(star)"
>★</span>
</div>
</template>
<script>
export default {
data() {
return {
currentStars: 0,
hoverStars: 0
}
},
methods: {
rate(star) {
this.currentStars = star
},
hover(star) {
this.hoverStars = star
},
resetHover() {
this.hoverStars = 0
},
getClass(star) {
return {
'active': star <= this.currentStars,
'hover': star <= this.hoverStars && star > this.currentStars
}
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
.star-rating span.hover {
color: #ffeb3b;
}
</style>
使用 SVG 图标
为了更好的视觉效果,可以使用 SVG 图标代替 Unicode 星星。
<template>
<div class="star-rating">
<svg
v-for="star in maxStars"
:key="star"
@click="rate(star)"
:class="{ 'filled': star <= currentStars }"
width="24"
height="24"
viewBox="0 0 24 24"
>
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
</svg>
</div>
</template>
添加动画效果
可以为星级评分添加简单的动画效果,提升用户体验。
<style>
.star-rating svg {
transition: all 0.2s ease;
}
.star-rating svg:hover {
transform: scale(1.2);
}
</style>
以上方法可以根据实际需求选择使用,组件库实现快速但自定义程度低,自定义实现灵活性高但需要更多代码。






