vue实现评价
Vue 实现评价功能
基本组件结构
使用 Vue 的单文件组件(SFC)实现评价功能,核心结构包括评分控件和评价表单。
<template>
<div class="rating-container">
<h3>发表评价</h3>
<div class="stars">
<span
v-for="star in 5"
:key="star"
@click="setRating(star)"
:class="{ 'active': star <= currentRating }"
>★</span>
</div>
<textarea v-model="comment" placeholder="请输入评价内容"></textarea>
<button @click="submitRating">提交评价</button>
</div>
</template>
数据与交互逻辑
通过 Vue 的响应式数据管理评分状态和评价内容。

<script>
export default {
data() {
return {
currentRating: 0,
comment: ''
}
},
methods: {
setRating(rating) {
this.currentRating = rating
},
submitRating() {
if (this.currentRating === 0) {
alert('请选择评分')
return
}
console.log('提交评价:', {
rating: this.currentRating,
comment: this.comment
})
// 实际项目中此处调用API提交数据
this.resetForm()
},
resetForm() {
this.currentRating = 0
this.comment = ''
}
}
}
</script>
样式设计
使用 CSS 增强交互视觉效果,例如悬停状态和选中状态。

<style scoped>
.rating-container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.stars span {
font-size: 2rem;
color: #ccc;
cursor: pointer;
transition: color 0.2s;
}
.stars span.active,
.stars span:hover {
color: #ffcc00;
}
.stars span:hover ~ span {
color: #ccc;
}
textarea {
width: 100%;
min-height: 100px;
margin: 15px 0;
}
button {
background: #42b983;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
</style>
进阶功能实现
对于需要显示历史评价的场景,可以添加评价列表组件。
<template>
<div class="review-list">
<div v-for="(review, index) in reviews" :key="index" class="review-item">
<div class="review-rating">
<span v-for="star in 5" :key="star" :class="{ 'active': star <= review.rating }">★</span>
</div>
<p class="review-content">{{ review.comment }}</p>
<p class="review-time">{{ review.time }}</p>
</div>
</div>
</template>
<script>
export default {
props: {
reviews: {
type: Array,
default: () => []
}
}
}
</script>
服务端交互
实际项目中通过 axios 与后端 API 通信,示例为提交评价的异步操作。
methods: {
async submitRating() {
try {
const response = await axios.post('/api/ratings', {
rating: this.currentRating,
comment: this.comment
})
this.$emit('rating-submitted', response.data)
this.resetForm()
} catch (error) {
console.error('评价提交失败:', error)
}
}
}
注意事项
- 使用 v-model 实现表单双向绑定
- 通过计算属性实现派生数据(如平均分)
- 考虑添加表单验证逻辑
- 对于敏感操作(如删除评价)需要添加确认对话框
以上实现可以根据实际需求进行扩展,例如添加图片上传、多维度评分等功能。






