vue实现星星
使用Vue实现星星评分组件
方法一:基础实现
创建Vue组件,使用v-for循环生成星星图标,通过点击事件切换选中状态
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="rate(index)"
:class="{ 'active': index < currentRating }"
>
★
</span>
</div>
</template>
<script>
export default {
data() {
return {
stars: Array(5).fill('★'),
currentRating: 0
}
},
methods: {
rate(index) {
this.currentRating = index + 1
}
}
}
</script>
<style>
.star-rating span {
font-size: 2rem;
color: #ccc;
cursor: pointer;
}
.star-rating span.active {
color: gold;
}
</style>
方法二:支持半星评分
通过计算属性处理半星显示逻辑,使用CSS实现半星效果
<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@mouseover="hoverRating = index + 1"
@mouseleave="hoverRating = 0"
@click="setRating(index + 1)"
>
<span class="star-background">★</span>
<span
class="star-foreground"
:style="{ width: getStarWidth(index) }"
>★</span>
</span>
</div>
</template>
<script>
export default {
props: {
value: Number,
maxStars: {
type: Number,
default: 5
}
},
data() {
return {
hoverRating: 0,
stars: Array(this.maxStars).fill('★')
}
},
computed: {
currentRating() {
return this.hoverRating || this.value
}
},
methods: {
setRating(rating) {
this.$emit('input', rating)
},
getStarWidth(index) {
const rating = this.currentRating
if (rating >= index + 1) return '100%'
if (rating > index) return `${(rating - index) * 100}%`
return '0%'
}
}
}
</style>
方法三:使用第三方图标库
结合Font Awesome等图标库实现更精美的星星效果
<template>
<div class="star-rating">
<i
v-for="index in maxStars"
:key="index"
:class="[
'fas',
index <= currentRating ? 'fa-star' : 'fa-star-o'
]"
@click="setRating(index)"
@mouseover="hoverRating = index"
@mouseleave="hoverRating = 0"
></i>
</div>
</template>
<script>
export default {
props: {
value: Number,
maxStars: {
type: Number,
default: 5
}
},
data() {
return {
hoverRating: 0
}
},
computed: {
currentRating() {
return this.hoverRating || this.value
}
},
methods: {
setRating(rating) {
this.$emit('input', rating)
}
}
}
</script>
注意事项

- 组件应支持双向绑定,使用v-model指令
- 可通过props自定义星星数量、大小和颜色
- 添加适当的过渡效果提升用户体验
- 考虑添加disabled状态防止误操作
- 对于移动端设备,需要添加触摸事件支持






