star组件(一共5分,5颗星,可以通过改变以下算法加星数)(多处有使用,抽成组件)
const LENGTH = 5;
const CLS_ON = 'on';
const CLS_HALF = 'half';
const CLS_OFF = 'off'; //先定义变量,方便修改
itemClasses() {
let result = [];
let score = Math.floor(this.score * 2) / 2; //向下0.5取整算法
let hasDecimal = score % 1 !== 0; //判断是否有小数
let integer = Math.floor(score); //取出分数的整数部分
for (let i = 0; i < integer; i++) { //添加填充的整星
result.push(CLS_ON);
}
if (hasDecimal) { //添加填充的半星,只可能有一颗半星
result.push(CLS_HALF);
}
while (result.length < LENGTH) { //剩余的添加上未填充的整星
result.push(CLS_OFF);
}
return result; //返回数组通过v-for填充
}
<template>
<div class="star" :class="starType">
<span v-for="(itemClass,index) in itemClasses" :class="itemClass" class="star-item" :key="index"></span>
</div>
</template>