vue实现评分星星
实现评分星星组件
在Vue中实现评分星星功能可以通过自定义组件完成。以下是一个常见的实现方式:
<template>
<div class="star-rating">
<span
v-for="star in maxStars"
:key="star"
@click="setRating(star)"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
:class="{
'star': true,
'active': star <= currentRating,
'hover': star <= hoverRating && hoverRating !== 0
}"
>
★
</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('rating-changed', star);
}
}
}
</script>
<style>
.star-rating {
font-size: 24px;
cursor: pointer;
}
.star {
color: #ccc;
display: inline-block;
transition: color 0.2s;
}
.star.active {
color: #ffcc00;
}
.star.hover {
color: #ffeb3b;
}
</style>
使用组件示例
<template>
<div>
<star-rating
:max-stars="5"
:initial-rating="3"
@rating-changed="handleRatingChange"
/>
<p>当前评分: {{ selectedRating }}</p>
</div>
</template>
<script>
import StarRating from './StarRating.vue';
export default {
components: {
StarRating
},
data() {
return {
selectedRating: 3
}
},
methods: {
handleRatingChange(rating) {
this.selectedRating = rating;
}
}
}
</script>
可选功能扩展
- 半星评分:可以通过修改CSS和逻辑来实现半星评分效果
- 只读模式:添加一个prop来控制是否允许用户交互
- 自定义星星图标:使用SVG或字体图标替代简单的★字符
- 大小控制:通过prop控制星星的大小
半星评分实现示例
<template>
<div class="star-rating">
<span
v-for="star in stars"
:key="star.index"
@click="setRating(star.value)"
@mouseover="hoverRating = star.value"
@mouseleave="hoverRating = 0"
:class="{
'star': true,
'active': star.value <= currentRating,
'hover': star.value <= hoverRating && hoverRating !== 0,
'half': star.isHalf && star.value - 0.5 <= currentRating && currentRating < star.value
}"
>
<span class="star-full">★</span>
<span class="star-half">★</span>
</span>
</div>
</template>
<script>
export default {
props: {
maxStars: {
type: Number,
default: 5
},
initialRating: {
type: Number,
default: 0
}
},
computed: {
stars() {
const stars = [];
for (let i = 1; i <= this.maxStars; i++) {
stars.push({
index: i,
value: i,
isHalf: false
});
stars.push({
index: i + 0.5,
value: i,
isHalf: true
});
}
return stars;
}
},
// 其余代码保持不变
}
</script>
<style>
.star {
position: relative;
display: inline-block;
width: 24px;
height: 24px;
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.star-full, .star-half {
position: absolute;
left: 0;
top: 0;
}
.star-half {
width: 50%;
overflow: hidden;
}
.star.active .star-full,
.star.hover .star-full {
color: #ffcc00;
}
.star.active .star-half,
.star.hover .star-half {
color: #ffcc00;
}
</style>
这些实现方式提供了基本的评分星星功能,可以根据具体需求进行调整和扩展。







