vue实现评分
Vue 实现评分功能
使用组件库实现
安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。
以 element-ui 为例:

<template>
<el-rate v-model="rating" :colors="colors"></el-rate>
</template>
<script>
export default {
data() {
return {
rating: 3,
colors: ['#99A9BF', '#F7BA2A', '#FF9900']
}
}
}
</script>
自定义评分组件
创建一个自定义的评分组件,使用 v-for 渲染星星图标,并通过点击事件更新评分。
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
:class="{ 'active': star <= currentRating }"
>★</span>
</div>
</template>
<script>
export default {
props: {
maxStars: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
}
},
data() {
return {
currentRating: this.initialRating
}
},
methods: {
setRating(star) {
this.currentRating = star
this.$emit('rating-changed', star)
}
}
}
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
使用 SVG 图标
如果需要更灵活的样式,可以使用 SVG 图标代替 Unicode 字符。

<template>
<div class="star-rating">
<svg
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
:class="{ 'active': star <= currentRating }"
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>
半星评分实现
如果需要支持半星评分,可以稍微修改逻辑。
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
@mousemove="setTempRating(star)"
@mouseleave="resetTempRating"
>
<span
v-if="tempRating >= star || (!tempRating && currentRating >= star)"
class="full"
>★</span>
<span
v-else-if="tempRating + 0.5 === star || (!tempRating && currentRating + 0.5 === star)"
class="half"
>½</span>
<span v-else class="empty">★</span>
</span>
</div>
</template>
动态颜色评分
根据评分值动态改变星星颜色。
computed: {
starColor() {
return [
'#ff4545', // 1星
'#ffa534', // 2星
'#ffe234', // 3星
'#b7dd29', // 4星
'#57e32c' // 5星
][this.currentRating - 1] || '#ccc'
}
}






