vue封装星星组件

效果图:
在这里插入图片描述

<template>
  <div>
    <div class="star mb-10" :class="starType">
      <span
        class="star-item"
        v-for="itemClass in itemClassess"
        :class="itemClass"
        track-by="$index"
      ></span>
    </div>
  </div>
</template>

<script>
const LENGTH = 5; //星星个数
const CLS_ON = "on"; //满星状态
const CLS_HALF = "half"; //半星状态
const CLS_OFF = "off"; //无星状态

export default {
  name: "xx",
  props: {
    size: {
      type: Number //  星星大小
    },
    score: {
      type: Number //  星星分数
    }
  },
  computed: {
    starType() {
      //设置星星尺寸
      return "star-" + this.size;
    },
    itemClassess() {
      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(CLS_ON);
      }
      //半星
      if (hasDecimal) {
        result.push(CLS_HALF);
      }
      //无星
      if (result.length < LENGTH) {
        result.push(CLS_OFF);
      }
      return result;
    }
  }
};
</script>

<style>
.star {
  display: flex;
  width: 100%;
}
.star-48 .star-item {
  width: 20px;
  height: 20px;
  margin-right: 22px;
  background-repeat: no-repeat;
  background-size: 20px 20px;
}
.star-48 .star-item:last-child {
  margin-right: 0px;
}
.star-48 .star-item.on {
  background-image: url("../../public/mx.png");  //满星图片 
}
.star-48 .star-item.half {
  background-image: url("../../public/bx.png");  //半星图片
}
.star-48 .star-item.off {
  background-image: url("../../public/wx.png");  //无星图片
}

.star-36 .star-item {
  width: 15px;
  height: 15px;
  margin-right: 6px;
  background-repeat: no-repeat;
  background-size: 15px 15px;
}
.star-36 .star-item:last-child {
  margin-right: 0px;
}
.star-36 .star-item:last-child {
  margin-right: 0px;
}
.star-36 .star-item.on {
  background-image: url("../../public/mx.png");  //满星图片 
}
.star-36 .star-item.half {
  background-image: url("../../public/bx.png");  //半星图片
}
.star-36 .star-item.off {
  background-image: url("../../public/wx.png");  //无星图片
}
</style>

在需要的组件中引入

import xx from "@/components/xx";
components: { xx }
<xx :size="48" :score="3"></xx>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值