vue实现豆瓣评分
Vue 实现豆瓣评分功能
实现豆瓣评分功能需要结合 Vue 的数据绑定和组件化特性,通常包括评分展示、交互评分和样式渲染。以下是具体实现方法:
数据准备
定义评分数据,通常豆瓣评分是 0-5 分,以半星为间隔(如 4.5 分)。在 Vue 的 data 中初始化评分:
data() {
return {
score: 4.5, // 当前评分
maxScore: 5, // 满分
isInteractive: false // 是否允许用户交互评分
}
}
评分渲染逻辑
使用 v-for 渲染星星,并通过计算属性判断是否显示全星、半星或空星:

computed: {
stars() {
const stars = []
for (let i = 1; i <= this.maxScore; i++) {
if (this.score >= i) {
stars.push('full') // 全星
} else if (this.score > i - 1) {
stars.push('half') // 半星
} else {
stars.push('empty') // 空星
}
}
return stars
}
}
模板部分
在模板中渲染星星,并根据交互状态绑定点击事件:
<div class="star-rating">
<span
v-for="(star, index) in stars"
:key="index"
@click="isInteractive ? setScore(index + 1) : null"
:class="['star', star]"
>
{{ star === 'full' ? '★' : star === 'half' ? '½' : '☆' }}
</span>
<span class="score-text">{{ score.toFixed(1) }}</span>
</div>
交互逻辑
如果允许用户评分,通过方法更新分数:

methods: {
setScore(newScore) {
this.score = newScore
}
}
样式优化
添加 CSS 美化评分组件,例如颜色和悬停效果:
.star-rating {
display: flex;
align-items: center;
font-size: 24px;
}
.star {
cursor: pointer;
color: #ccc;
margin-right: 2px;
}
.star.full {
color: #ffac2d;
}
.star.half {
position: relative;
}
.star.half:after {
content: '★';
position: absolute;
left: 0;
width: 50%;
overflow: hidden;
color: #ffac2d;
}
.score-text {
margin-left: 8px;
font-size: 16px;
color: #666;
}
动态半星实现
更精确的半星可以通过 SVG 或 CSS 渐变实现。例如使用 CSS 伪元素控制半星宽度:
.star.half {
position: relative;
display: inline-block;
}
.star.half:before {
content: '★';
position: absolute;
width: 50%;
overflow: hidden;
color: #ffac2d;
}
组件化封装
将评分功能封装为可复用组件,通过 props 接收参数:
props: {
value: {
type: Number,
default: 0
},
interactive: {
type: Boolean,
default: false
}
}
通过以上步骤,可以实现一个功能完整且样式美观的豆瓣评分组件,支持展示静态评分或用户交互评分。






