vue实现星星
实现星星评分的Vue组件
使用Vue实现星星评分功能可以通过组件化方式完成,以下是一个完整的实现方案:
模板部分
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="rate(index + 1)"
@mouseover="hover(index + 1)"
@mouseleave="reset"
:class="['star', { 'filled': index < currentRating }]"
>
★
</span>
</div>
</template>
脚本部分

<script>
export default {
props: {
maxRating: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
}
},
data() {
return {
stars: Array(this.maxRating).fill(null),
currentRating: this.initialRating,
tempRating: 0
}
},
methods: {
rate(rating) {
this.currentRating = rating
this.$emit('rating-selected', rating)
},
hover(rating) {
this.tempRating = rating
},
reset() {
this.tempRating = 0
}
},
computed: {
filledStars() {
return this.tempRating || this.currentRating
}
}
}
</script>
样式部分
<style scoped>
.star-rating {
font-size: 24px;
display: inline-flex;
}
.star {
color: #ccc;
cursor: pointer;
transition: color 0.2s;
}
.star.filled {
color: gold;
}
.star:hover {
color: gold;
}
</style>
使用组件的方法
在父组件中引入并使用星星评分组件:

<template>
<div>
<star-rating
:max-rating="5"
:initial-rating="3"
@rating-selected="handleRating"
/>
<p>当前评分: {{ selectedRating }}</p>
</div>
</template>
<script>
import StarRating from './StarRating.vue'
export default {
components: {
StarRating
},
data() {
return {
selectedRating: 3
}
},
methods: {
handleRating(rating) {
this.selectedRating = rating
}
}
}
</script>
实现半星功能
如果需要实现半星评分,可以修改组件如下:
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="rate(index + 0.5)"
@dblclick="rate(index + 1)"
@mouseover="hover(index + 0.5)"
@mouseout="reset"
>
<span
class="star-half"
:class="{ 'active': index + 0.5 <= filledStars }"
></span>
<span
class="star"
:class="{ 'active': index + 1 <= filledStars }"
></span>
</span>
</div>
</template>
实现只读星星
如果需要显示只读的星星评分:
<template>
<div class="star-rating readonly">
<span
v-for="(star, index) in stars"
:key="index"
:class="['star', { 'filled': index < currentRating }]"
>
★
</span>
</div>
</template>
<script>
export default {
props: {
rating: {
type: Number,
required: true
},
maxRating: {
type: Number,
default: 5
}
},
data() {
return {
stars: Array(this.maxRating).fill(null),
currentRating: this.rating
}
}
}
</script>
<style scoped>
.readonly .star {
cursor: default;
}
.readonly .star:hover {
color: inherit;
}
</style>
这些实现方案覆盖了从基础到进阶的星星评分需求,可以根据具体项目要求选择合适的实现方式。






