Vue简单的实现五星级评分

效果:

原理:

类似于四舍五入的方法,不同点在于四舍五入是把数字转成整数,而这个方法是把分数转成整数或(整数+0.5),有点抽象,举个例子就明白了,例如 把4.7转成4.5(即四个半星),4.3转成4.0(即四个星),4.0就是四个星。

需要准备三张星星图片,即全星,半星,空星。

代码:

<template>
  <div class="score">
    <!--循序生成五星,原理是通过给span绑定类名设置星星背景图-->
    <span class="star-item" v-for="star in starScore" :class="star"></span>
    <span>{{temp}}</span>
  </div>
</template>

<script>
    export default {
        name: "Score",
      data(){
        return {
          temp:4.3
        }
      },
      computed:{
        starScore(){
          let stars = [];   //定义一个空数组来存储类名
          let score = Math.floor(this.temp * 2)/2;   //把评分转成整数或整数+0.5(如:4.7转成4.5,4.2转成4.0)
          let decimalScore = score%1 !== 0;   //取1的余数不等于0,说明有小数(显示半星)
          let integerScore = Math.floor(score);   //取整数分数(显示全星)
          for (let i=0; i<integerScore; i++){
            stars.push('on')      //整数分数为多少,就添加多少个全星
          }
          if (decimalScore){
            stars.push('half')    //存在小数分数,添加一个半星
          }
          while(stars.length<5){
            stars.push('off')     //如果星星数不满5颗,空星星填充
          }
          return stars
        }
      }
    }
</script>

<style scoped lang="less">
  .score{
    display: flex;
    align-items: center;
    justify-content: center;
    .star-item{
      width: 20px;
      height: 20px;
      display: inline-block;
      margin: 0 5px;
      background: no-repeat;
    }
    .star-item.on{
      background: url("../../assets/star/[email protected]");  //全星
    }
    .star-item.half{
      background: url("../../assets/star/[email protected]");  //半星
    }
    .star-item.off{
      background: url("../../assets/star/[email protected]");   //空星星
    }
  }
</style>

(完)

参考文章:http://baijiahao.baidu.com/s?id=1581695099833705869&wfr=spider&for=pc

猜你喜欢

转载自blog.csdn.net/Mr_JavaScript/article/details/81738426