vue 實現的評分小星星組件,包括半星


github源碼地址:https://github.com/13476075014/node-vue/blob/master/mynodeproject/13.sell/sell/src/components/star/star.vue

 

一:實現的思路:

  通過評分的分數,來算出高亮的全星有幾顆,有沒有半星,灰色星星有幾顆,通過背景圖片實現,例如:

    評分 : 4.6 分 

    四舍五入計算把分數換算成0.5的倍數:Math.floor( 4.6 *2 ) / 2   等於 4.5

    把星星放到數組 arr_star 里面:

      是否需要半星  var half = 4.5 % 1 != 0 ?  true :false    //能被1取余整數的話就不需要半星為false,否則是true

      把全星push到數組里面   for ( var i = 0; i< Math.floor( 4.5) ;i++ ) {  arr_star.push( "on")  }  //on是星星高亮的圖片名字

      把半星放到數組里面  if( half ) { arr_star.push( "half" ) }  //half是半星圖片的名字

      把灰色星星放到數組里面  if( arr_star.length < 5) { 

                    for( var i=0;i<(5-arr_star.length) ; i++ ){  arr_star.push( "off" ) }   //off是灰色星星的名字

二:具體實現代碼:

  2.1 html部分:

    

<template>
  <div class="star">
    <span v-for="(item,index) in itemClasslass" class="star-item" :key="index" :class="item"></span>
  </div>
</template>

  2.2 js部分

<script>
const lengths = 5;
const starOn = 'on';
const starHalf = 'half';
const starOff = 'off';

  export default({
    data(){
      return {

      }
    },
    props:{
      score:{//分數
        type:Number,
        default:function(){
          return 5
        }
      }
    },
    created() {
    },
    computed:{
      itemClasslass(){//星星的數組
          let result = [];
          let score = Math.floor(this.score * 2) / 2; //例如:把分數處理成在4.5以上及4.5就變成向上取整5,在4.5以下就變成4.5


          //是否需要半星
          let starhalf = score%1 != 0 ? true : false ;

          //幾顆全星
          let fullstar = Math.floor(score);
          for(var i=0 ; i<fullstar;i++){//放全星
            result.push(starOn);
          }
          if(starhalf){//放半星
            result.push(starHalf)
          }
          if(result.length < lengths){//如果沒有滿到五個星就用灰色的星星補齊9
            var offstar = lengths - result.length;
            for(var i=0;i<offstar;i++){
                result.push(starOff);
            }
          };
          return result;
      }
    }
  })
</script>

  2.3 css部分

<style lang="stylus" scoped>
// @import "../../common/stylus/mixin";

  .star
    .star-item
      display inline-block
      background-repeat no-repeat
      width 20px
      height 20px
      margin-right 22px
      background-size 20px 20px
      &:last-child
        margin-right 0
      &.on
        bg-image(on')  /* 這個是在公用的stylus中的方法:
                bg-image($url)
                  background-image url("../../assets/images/" + $url + "@2x.png")
              */
      &.half
        bg-image('half')
      &.off
        bg-image('off')  


</style>

三:具體效果:

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM