vue实现星星
Vue 实现星星评分组件
使用 Vue 实现星星评分功能可以通过自定义组件完成,以下是两种常见实现方式:
基础实现(静态评分)
<template>
<div class="star-rating">
<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>
.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="index in 5"
:key="index"
@mouseover="hoverRating = index"
@mouseleave="hoverRating = 0"
@click="setRating(index)"
>
<span v-if="index <= currentRating">★</span>
<span v-else-if="index - 0.5 <= currentRating">½</span>
<span v-else>☆</span>
</span>
</div>
</template>
<script>
export default {
data() {
return {
currentRating: 0,
hoverRating: 0
}
},
methods: {
setRating(rating) {
this.currentRating = rating
}
}
}
</script>
<style>
.star-rating {
font-size: 24px;
}
.star-rating span {
color: gold;
cursor: pointer;
}
</style>
使用第三方库实现
对于更复杂的评分需求,可以考虑使用现成的 Vue 评分组件库:
-
安装
vue-star-rating库:
npm install vue-star-rating -
在组件中使用:
<template> <star-rating :rating="rating" @rating-selected="setRating" :star-size="30" :rounded-corners="true" :border-width="2" /> </template>
export default { components: { StarRating }, data() { return { rating: 3.5 } }, methods: { setRating(rating) { this.rating = rating } } }
```自定义 SVG 星星实现
如果需要完全自定义星星样式,可以使用 SVG:
<template>
<div class="star-container">
<svg
v-for="i in 5"
:key="i"
@click="setRating(i)"
:class="{ 'filled': i <= 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>
<script>
export default {
data() {
return {
currentRating: 0
}
},
methods: {
setRating(rating) {
this.currentRating = rating
}
}
}
</script>
<style>
.star-container svg {
fill: #ddd;
cursor: pointer;
margin-right: 5px;
}
.star-container svg.filled {
fill: #ffc107;
}
</style>
以上实现方式可根据实际需求选择或组合使用,基础实现适合简单评分场景,第三方库提供更多配置选项,SVG 实现则允许完全自定义星星样式。






