一、评分
html
<img v-for="(star,index) in stars" :src="star.src" @click="rating(index)" style="width:24px;height:24px;vertical-align: middle;" />
<span class="scoreText"> {{starNum}}分 </span>
js
//星星的图片路径
var starOffImg = "images/star_off.png";
var starOnImg = "images/star_on.png";
data:{
starNum: 0,//分数
stars: [//星星数组
{
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
},
{
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
}
]
},
rating: function (index) {//评分
var total = this.stars.length; //星星总数
var idx = index + 1; //这代表选的第idx颗星-也代表应该显示的星星数量
//进入if说明页面为初始状态
if (this.starNum == 0) {
this.starNum = idx;
for (var i = 0; i < idx; i++) {
this.stars[i].src = starOnImg;
this.stars[i].active = true;
}
} else {
//如果再次点击当前选中的星级-仅取消掉当前星级,保留之前的。
if (idx == this.starNum) {
for (var i = index; i < total; i++) {
this.stars[i].src = starOffImg;
this.stars[i].active = false;
}
}
//如果小于当前最高星级,则直接保留当前星级
if (idx < this.starNum) {
for (var i = idx; i < this.starNum; i++) {
this.stars[i].src = starOffImg;
this.stars[i].active = false;
}
}
//如果大于当前星级,则直接选到该星级
if (idx > this.starNum) {
for (var i = 0; i < idx; i++) {
this.stars[i].src = starOnImg;
this.stars[i].active = true;
}
}
var count = 0; //计数器-统计当前有几颗星
for (var i = 0; i < total; i++) {
if (this.stars[i].active) {
count++;
}
}
this.starNum = count;
}
}
评分:
点击后
二、显示评分
html
<span v-for="(itemClass,index) in itemClasses" :class="itemClass" class="star-item" track-by="index"> </span>
<span style="display:inline-block;width:50px;height:30px;line-height:30px">{{score}}分</span>
css
.star-item {
display: inline-block;
background-repeat: no-repeat;
width: 20px;
height: 20px;
margin-right: 10px;
background-size: 100%;
}
.star-item.on {
background-image: url(../images/star_on.png);
}
.star-item.half {
background-image: url(../images/star_half.png);
}
.star-item.off {
background-image: url(../images/star_off.png);
}
js
var app = new Vue({
el: '#app',
data: {
score: 3.5
},
computed: { //计算属性
itemClasses() {
let result = [];
let score = Math.floor(this.score * 2) / 2;
let hasDecimal = score % 1 !== 0;
let integer = Math.floor(score);
for (let i = 0; i < integer; i++) {
result.push("on");
}
if (hasDecimal) {
result.push("half");
}
while (result.length < 5) {
result.push("off");
}
return result;
}
}
})
显示:
参考链接: 3行核心css代码的rate评分组件
我还写了小程序实现的微信小程序——自定义评分组件