off,half,on
star组件要从后台接受的score数据然后通过计算输出相应的图案。
一,在计算属性中,要计算出需要几个on,half,off
定义对应的变量:
const LENGTH = 5; const CLA_ON = 'on'; const CLA_HALF = 'half'; const CLA_OFF = 'off';
1,
let score = Math.floor(this.score * 2) / 2; let hasDecimal = score % 1 !== 0;
计算出是否含有half,hasDecimal返回值为true/false(math.floor(x)返回小于参数x的最大整数,即对浮点数向下取整。x[]的取值。)
2,
let integer=Math.floor(score);
integer的值是计算出on的个数
二,将所计算的数对应的值,存入数组里,在HTML中我们是要按顺序输出数组里的值的,所以在存的时候也要按照对应的顺序。
1,
for (let i=0; i<integer;i++){ result.push(CLA_ON); }
存入为on的数据,
2,
if (hasDecimal){ result.push(CLA_HALF) }
hasDecimal返回值为true/false,如果为true,则存入一个half。
3,
while (result.length<LENGTH){ result.push(CLA_OFF) }
判断数组是否满了,不满就存入off
例如score的值为3.7,则 integer的值是为3,hasDecimal的值为true,存入后的数组则为['on','on','on','half','off']。最后展现的则为
star组件的全部代码:
HTML:
<template> <div class="star"> <span v-for="item in itemsClass" :class="item" class="star-item">{{item}}</span> </div> </template>
js:
<script> const LENGTH = 5; const CLA_ON = 'on'; const CLA_HALF = 'half'; const CLA_OFF = 'off'; export default { name: "star", props: { score: { type: Number } }, computed: { itemsClass() { 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(CLA_ON); } if (hasDecimal){ result.push(CLA_HALF) } while (result.length<LENGTH){ result.push(CLA_OFF) } return result; } } } </script>
css:
<style scoped> .star { font-size: 0; } .star-item { width: 20px; height: 20px; margin-right: 20px; background-size: 20px 20px; display: inline-block; background-repeat: no-repeat; } .on { background-image: url("star48_on@2x.png"); } .half { background-image: url("star48_half@2x.png"); } .off { background-image: url("star48_off@2x.png"); } </style>