vue怎么实现淘宝打分
Vue 实现淘宝评分功能
淘宝评分功能通常是一个五星评分系统,用户可以通过点击星星来选择评分。以下是使用 Vue 实现类似功能的步骤:
创建评分组件
<template>
<div class="star-rating">
<span
v-for="star in 5"
:key="star"
@click="setRating(star)"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
:class="['star', { 'active': star <= (hoverRating || currentRating) }]"
>
★
</span>
</div>
</template>
<script>
export default {
data() {
return {
currentRating: 0,
hoverRating: 0
}
},
methods: {
setRating(star) {
this.currentRating = star
this.$emit('rating-selected', star)
}
}
}
</script>
<style>
.star-rating {
font-size: 24px;
}
.star {
color: #ccc;
cursor: pointer;
transition: color 0.2s;
}
.star.active {
color: #ff9900;
}
</style>
使用评分组件
在父组件中引入并使用评分组件:
<template>
<div>
<h3>请为商品评分:</h3>
<star-rating @rating-selected="handleRating"></star-rating>
<p>当前评分:{{ selectedRating }}</p>
</div>
</template>
<script>
import StarRating from './StarRating.vue'
export default {
components: {
StarRating
},
data() {
return {
selectedRating: 0
}
},
methods: {
handleRating(rating) {
this.selectedRating = rating
}
}
}
</script>
添加半星评分功能(可选)
如果需要实现半星评分效果:
<template>
<div class="star-rating">
<span
v-for="star in 5"
:key="star"
@click="setRating(star)"
@mouseover="hoverRating = star"
@mouseleave="hoverRating = 0"
>
<span
class="star-half"
:class="{ 'active': star - 0.5 <= (hoverRating || currentRating) }"
@click="setRating(star - 0.5)"
></span>
<span
class="star"
:class="{ 'active': star <= (hoverRating || currentRating) }"
></span>
</span>
</div>
</template>
<style>
.star, .star-half {
display: inline-block;
width: 12px;
height: 24px;
overflow: hidden;
position: relative;
}
.star:before, .star-half:before {
content: "★";
position: absolute;
font-size: 24px;
color: #ccc;
}
.star-half:before {
left: -12px;
}
.star.active:before, .star-half.active:before {
color: #ff9900;
}
</style>
添加评分文字提示
可以添加评分文字提示,类似淘宝的"差"、"一般"、"好"等:
<template>
<div>
<star-rating @rating-selected="handleRating"></star-rating>
<p class="rating-text">{{ ratingText }}</p>
</div>
</template>
<script>
export default {
computed: {
ratingText() {
const texts = ['', '非常差', '差', '一般', '好', '非常好']
return texts[this.selectedRating] || ''
}
}
}
</script>
实现只读评分显示
对于已完成的评分展示,可以创建只读版本:
<template>
<div class="star-rating readonly">
<span
v-for="star in 5"
:key="star"
:class="['star', { 'active': star <= currentRating }]"
>
★
</span>
</div>
</template>
<style>
.star-rating.readonly .star {
cursor: default;
}
</style>
这些代码实现了一个完整的淘宝风格评分系统,包含交互效果和视觉反馈。可以根据实际需求调整样式和功能。







