vue 实现星星评分
vue 实现星星评分的方法
使用组件化方式实现
创建一个独立的评分组件,通过v-for循环生成星星图标,利用v-model或props实现数据双向绑定。

<template>
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="setRating(index + 1)"
:class="['star', { 'filled': index < modelValue }]"
>
★
</span>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0
}
},
data() {
return {
stars: Array(5).fill(null)
}
},
methods: {
setRating(rating) {
this.$emit('update:modelValue', rating)
}
}
}
</script>
<style>
.star {
font-size: 24px;
color: #ccc;
cursor: pointer;
}
.filled {
color: gold;
}
</style>
使用第三方库
安装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, index) in stars"
:key="index"
@click="setRating(index + 1)"
>
<span class="star-container">
<span class="star-background">★</span>
<span
class="star-foreground"
:style="{ width: getStarWidth(index) }"
>★</span>
</span>
</span>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0
}
},
data() {
return {
stars: Array(5).fill(null)
}
},
methods: {
setRating(rating) {
this.$emit('update:modelValue', rating)
},
getStarWidth(index) {
const rating = this.modelValue
if (rating >= index + 1) return '100%'
if (rating > index) return `${(rating - index) * 100}%`
return '0%'
}
}
}
</script>
<style>
.star-container {
position: relative;
display: inline-block;
}
.star-background {
color: #ccc;
}
.star-foreground {
position: absolute;
left: 0;
top: 0;
color: gold;
overflow: hidden;
white-space: nowrap;
}
</style>
使用SVG实现矢量星星
通过SVG路径绘制星星,可以获得更好的视觉效果和动画可能性。
<template>
<div class="star-rating">
<svg
v-for="(star, index) in stars"
:key="index"
@click="setRating(index + 1)"
width="24"
height="24"
viewBox="0 0 24 24"
>
<path
:d="starPath"
:fill="index < modelValue ? 'gold' : '#ccc'"
/>
</svg>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0
}
},
data() {
return {
stars: Array(5).fill(null),
starPath: "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"
}
},
methods: {
setRating(rating) {
this.$emit('update:modelValue', rating)
}
}
}
</script>
这些方法提供了从简单到复杂的星星评分实现方案,可根据项目需求选择适合的方式。组件化实现便于复用,第三方库节省开发时间,SVG方案则提供最佳的视觉效果。






