vue实现简单的评分组件(五角星、评分)

<template>
  <div class="star">
    <span class="star-item on"></span>
    <span class="star-item off"></span>
    <span class="star-item half"></span>
    <hr>
    <span class="star-item" v-for="(item, index) in starList" :key="index" :class="item"></span>
  </div>
</template>
<script>
export default {
  data() {
    return { score: 3.9 }
  },
  computed: {
    starList: function () {
      let result = []
      const score = Math.floor(this.score * 2) / 2 // 4.7 -> 4.5    4.2 -> 4
      const integer = Math.floor(score)
      const hasDecimal = score % 1 !== 0
      // 先将on添加到list中
      for (let i = 0; i < integer; i++) {
        result.push('on')
      }
      // 将半选添加到list
      if (hasDecimal) result.push('half')
      // 若不满5个,剩下的添加off直到满5个为止
      for (let i = result.length; i < 5; i++) {
        result.push('off')
      }
      return result
    }
  }
}
</script>
<style lang="less" scoped>
.star-item {
  display: inline-block;
  width: 50px;
  height: 50px;
  background-size: 50px 50px;
  &.on {
    background-image: url('./star/star-on.png');
  }
  &.off {
    background-image: url('./star/star-off.png');
  }
  &.half {
    background-image: url('./star/star-half.png');
  }
}
</style>

posted @ 2021-08-23 23:28  吴小明-  阅读(1848)  评论(0编辑  收藏  举报