vue实现星星评分
Vue 实现星星评分
在 Vue 中实现星星评分功能,可以通过自定义组件或使用第三方库来完成。以下是两种常见实现方式:
自定义星星评分组件
创建一个可复用的星星评分组件,支持点击和悬停交互:

<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="rate(star)"
@mouseover="hover(star)"
@mouseleave="resetRating"
: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,
tempRating: 0
};
},
methods: {
rate(star) {
this.currentRating = star;
this.$emit('rated', star);
},
hover(star) {
this.tempRating = this.currentRating;
this.currentRating = star;
},
resetRating() {
this.currentRating = this.tempRating;
}
}
};
</script>
<style scoped>
.star-rating {
font-size: 24px;
}
.star-rating span {
color: #ccc;
cursor: pointer;
}
.star-rating .active {
color: gold;
}
</style>
使用方法:
<star-rating
:max-stars="5"
:initial-rating="3"
@rated="handleRating"
/>
使用第三方库
安装 vue-star-rating 库:

npm install vue-star-rating
使用示例:
<template>
<star-rating
v-model:rating="rating"
:increment="0.5"
:star-size="30"
/>
</template>
<script>
import StarRating from 'vue-star-rating';
export default {
components: {
StarRating
},
data() {
return {
rating: 3.5
};
}
};
</script>
半星评分实现
如果需要支持半星评分,可以修改自定义组件:
<template>
<div class="star-rating">
<span
v-for="star in starsArray"
:key="star.index"
@click="rate(star.value)"
@mouseover="hover(star.value)"
@mouseleave="resetRating"
:class="getStarClass(star.value)"
>
{{ star.isHalf ? '½' : '★' }}
</span>
</div>
</template>
<script>
export default {
props: {
maxStars: {
type: Number,
default: 5
},
increment: {
type: Number,
default: 1
},
initialRating: {
type: Number,
default: 0
}
},
computed: {
starsArray() {
const stars = [];
for (let i = 1; i <= this.maxStars; i++) {
stars.push({
index: i,
value: i,
isHalf: false
});
if (this.increment === 0.5 && i < this.maxStars) {
stars.push({
index: i + 0.5,
value: i + 0.5,
isHalf: true
});
}
}
return stars;
}
},
// 其余代码与前面示例相同
};
</script>



