vue实现等级打分
Vue 实现等级打分功能
等级打分功能通常用于评分、星级评价等场景。以下是几种常见的实现方式:
使用 SVG 或字体图标实现
通过 v-for 循环生成多个图标,根据当前评分高亮对应数量的图标:

<template>
<div>
<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>
span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.active {
color: gold;
}
</style>
使用第三方组件库
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>
实现半星评分功能
通过计算显示部分星星:

<template>
<div>
<span
v-for="star in 5"
:key="star"
@click="setRating(star)"
>
<span v-if="star <= fullStars">★</span>
<span v-else-if="star === fullStars + 1 && hasHalfStar">½</span>
<span v-else>☆</span>
</span>
</div>
</template>
<script>
export default {
props: {
value: Number
},
computed: {
fullStars() {
return Math.floor(this.value)
},
hasHalfStar() {
return this.value % 1 >= 0.5
}
},
methods: {
setRating(star) {
this.$emit('input', star)
}
}
}
</script>
使用 CSS 自定义样式
通过纯 CSS 实现更灵活的样式控制:
<template>
<div class="rating">
<input
v-for="i in 5"
:key="i"
type="radio"
:id="'star'+i"
:value="i"
v-model="rating"
>
<label
v-for="i in 5"
:key="'label'+i"
:for="'star'+i"
></label>
</div>
</template>
<script>
export default {
data() {
return {
rating: 0
}
}
}
</script>
<style>
.rating {
display: inline-flex;
flex-direction: row-reverse;
}
.rating input {
display: none;
}
.rating label {
width: 20px;
height: 20px;
background: #ccc;
cursor: pointer;
}
.rating input:checked ~ label {
background: gold;
}
</style>
实现可自定义数量的评分项
通过 props 接收评分项数量:
<template>
<div>
<span
v-for="n in maxRating"
:key="n"
@click="$emit('update:modelValue', n)"
:class="{ 'active': n <= modelValue }"
>
{{ icon }}
</span>
</div>
</template>
<script>
export default {
props: {
modelValue: Number,
maxRating: {
type: Number,
default: 5
},
icon: {
type: String,
default: '★'
}
}
}
</script>
这些实现方式可以根据具体需求进行组合和扩展,创建出符合项目需求的等级打分功能。






