评分以五颗星展示封装组件

评分以五颗星展示封装组件

第一步接收score和size(代表评分和五角星大小)

props: {
	score: Number,
    size: Number
}

HTML部分

<template>
  <div class="star" :class="`star-${size}`">
    <p class="star-item" v-for="(sc, index) in starClasses" :key="index" :class="sc"></p>
  </div>
</template>

CSS部分:设计三种大小样式。通过:class="star-${size}"决定使用那一种

.star {
  display: flex;
}
.star-48 {
  .star-item {
    width: 20px;
    height: 20px;
    margin-right: 22px;
    background-size: 20px 20px;
    &.on {
      background-image: url('./img/[email protected]');
    }
    &.half {
      background-image: url('./img/[email protected]');
    }
    &.off {
      background-image: url('./img/[email protected]');
    }
  }
}
.star-36 {
  .star-item {
    width: 15px;
    height: 15px;
    margin-right: 6px;
    background-size: 15px 15px;
    &.on {
      background-image: url('./img/[email protected]');
    }
    &.half {
      background-image: url('./img/[email protected]');
    }
    &.off {
      background-image: url('./img/[email protected]');
    }
  }
}
.star-24 {
  .star-item {
    width: 10px;
    height: 10px;
    margin-right: 3px;
    background-size: 10px 10px;
    &.on {
      background-image: url('./img/[email protected]');
    }
    &.half {
      background-image: url('./img/[email protected]');
    }
    &.off {
      background-image: url('./img/[email protected]');
    }
  }
}

JavaScript部分:根据score,得到监听属性starClasses数组,绑定样式:class="sc"

computed: {
    starClasses() {
      const scs = []
      //向scs中添加'on','half','off'
      //3.2  3 + 0 + 2
      //3.5  3 + 1 + 1
      //4.5  4 + 1 + 0
      const scoreInt = Math.floor(this.score)
      for (let i = 0; i < scoreInt; i++) {
        scs.push('on')
      }
      if (this.score * 10 - scoreInt * 10 >= 5) {
        scs.push('half')
      }
      while (scs.length < 5) {
        scs.push('off')
      }
      return scs
    }
  }

你可能感兴趣的:(评分以五颗星展示封装组件)