vue实现评分
实现评分功能的基本方法
使用Vue实现评分功能可以通过多种方式完成,常见的方法包括基于组件、自定义指令或第三方库。以下是几种典型实现方案。
基于组件的评分实现
创建一个可复用的评分组件,利用v-for渲染星星图标,并通过点击事件动态更新评分值。
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
:class="{ 'active': star <= (hoverRating || currentRating) }"
>
★
</span>
</div>
</template>
<script>
export default {
props: {
maxStars: { type: Number, default: 5 },
initialRating: { type: Number, default: 0 }
},
data() {
return {
currentRating: this.initialRating,
hoverRating: 0
};
},
methods: {
setRating(star) {
this.currentRating = star;
this.$emit('rated', star);
}
}
};
</script>
<style>
.star-rating span {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
使用第三方库(如vue-star-rating)
安装vue-star-rating库简化实现:
npm install vue-star-rating
组件调用示例:
<template>
<star-rating
v-model="rating"
:increment="0.5"
:show-rating="false"
/>
</template>
<script>
import StarRating from 'vue-star-rating';
export default {
components: { StarRating },
data() {
return { rating: 3.5 };
}
};
</script>
动态评分与半星效果
通过CSS和计算属性实现半星评分效果:
<template>
<div class="half-star-rating">
<div
v-for="star in stars"
:key="star.index"
@click="setRating(star.value)"
class="star-container"
>
<div class="star-background">★</div>
<div
class="star-foreground"
:style="{ width: star.fill + '%' }"
>★</div>
</div>
</div>
</template>
<script>
export default {
props: { max: { type: Number, default: 5 } },
data() {
return { rating: 0 };
},
computed: {
stars() {
return Array.from({ length: this.max }, (_, i) => ({
index: i,
value: i + 1,
fill: Math.min(100, Math.max(0, (this.rating - i) * 100))
}));
}
},
methods: {
setRating(val) {
this.rating = val;
}
}
};
</script>
<style>
.half-star-rating {
display: flex;
}
.star-container {
position: relative;
font-size: 24px;
cursor: pointer;
}
.star-background {
color: #ccc;
}
.star-foreground {
position: absolute;
top: 0;
left: 0;
width: 0;
color: gold;
overflow: hidden;
white-space: nowrap;
}
</style>
表单集成与数据绑定
将评分组件与Vue表单系统集成:
<template>
<form @submit.prevent="submitReview">
<star-rating v-model="formData.rating"></star-rating>
<button type="submit">提交评价</button>
</form>
</template>
<script>
export default {
data() {
return {
formData: { rating: 0 }
};
},
methods: {
submitReview() {
console.log('提交评分:', this.formData.rating);
}
}
};
</script>
无障碍优化
为评分组件添加ARIA属性提升可访问性:
<span
role="radio"
:aria-checked="star <= currentRating"
:aria-posinset="star"
:aria-setsize="maxStars"
tabindex="0"
@keydown.space.prevent="setRating(star)"
>
★
</span>
以上方案可根据实际需求选择或组合使用。组件化实现适合需要高度定制的场景,第三方库能快速实现标准功能,而半星效果和表单集成则增强了用户体验和数据管理能力。







