vue实现好评差评
Vue 实现好评差评功能
在 Vue 中实现好评差评功能,可以通过组件化方式构建评分系统。以下是具体实现方法:
1. 创建评分组件
<template>
<div class="rating">
<span
v-for="star in stars"
:key="star"
@click="setRating(star)"
:class="{ 'active': star <= currentRating }"
>
{{ star <= currentRating ? '★' : '☆' }}
</span>
<p>{{ ratingText }}</p>
</div>
</template>
<script>
export default {
props: {
maxStars: {
type: Number,
default: 5
}
},
data() {
return {
currentRating: 0,
stars: Array.from({length: this.maxStars}, (_, i) => i + 1)
}
},
computed: {
ratingText() {
if (this.currentRating <= 2) return '差评'
if (this.currentRating >= 4) return '好评'
return '一般'
}
},
methods: {
setRating(star) {
this.currentRating = star
this.$emit('rating-selected', star)
}
}
}
</script>
<style>
.rating span {
font-size: 24px;
cursor: pointer;
color: #ccc;
}
.rating span.active {
color: gold;
}
</style>
2. 在父组件中使用
<template>
<div>
<h3>请评价我们的服务</h3>
<RatingComponent
@rating-selected="handleRating"
/>
<p v-if="selectedRating">您选择了: {{ selectedRating }}星</p>
</div>
</template>
<script>
import RatingComponent from './RatingComponent.vue'
export default {
components: {
RatingComponent
},
data() {
return {
selectedRating: null
}
},
methods: {
handleRating(rating) {
this.selectedRating = rating
// 可以在这里发送API请求保存评价
}
}
}
</script>
3. 扩展功能
对于更复杂的评价系统,可以添加以下功能:
- 评价文字内容输入框
- 提交按钮和验证逻辑
- 显示历史评价数据
- 动画效果增强用户体验
4. 数据存储
通常需要将评价数据发送到后端API保存:
methods: {
async submitRating() {
try {
const response = await axios.post('/api/ratings', {
rating: this.selectedRating,
comment: this.comment
})
console.log('评价提交成功', response.data)
} catch (error) {
console.error('提交评价失败', error)
}
}
}
5. 显示评价统计
可以创建另一个组件来显示评价统计数据:
<template>
<div class="rating-stats">
<div v-for="n in 5" :key="n">
{{ n }}星: {{ getStarCount(n) }} ({{ getPercentage(n) }}%)
<div class="progress-bar" :style="{ width: getPercentage(n) + '%' }"></div>
</div>
<p>平均评分: {{ averageRating.toFixed(1) }}</p>
</div>
</template>
<script>
export default {
props: {
ratings: {
type: Array,
required: true
}
},
computed: {
averageRating() {
return this.ratings.reduce((a, b) => a + b, 0) / this.ratings.length
}
},
methods: {
getStarCount(star) {
return this.ratings.filter(r => r === star).length
},
getPercentage(star) {
return (this.getStarCount(star) / this.ratings.length) * 100
}
}
}
</script>
以上实现提供了完整的评价系统功能,包括用户交互、数据存储和统计展示。根据实际需求可以进一步调整样式和功能。

