Vue2.0 高仿饿了吗的实践-star组件的实现

off,half,on

star组件要从后台接受的score数据然后通过计算输出相应的图案。

一,在计算属性中,要计算出需要几个on,half,off

定义对应的变量:

 const LENGTH = 5;
  const CLA_ON = 'on';
  const CLA_HALF = 'half';
  const CLA_OFF = 'off';

         1,

let score = Math.floor(this.score * 2) / 2;
        let hasDecimal = score % 1 !== 0; 

          计算出是否含有half,hasDecimal返回值为true/false(math.floor(x)返回小于参数x的最大整数,即对浮点数向下取整。x[]的取值。

       2,

 let integer=Math.floor(score);

        integer的值是计算出on的个数

二,将所计算的数对应的值,存入数组里,在HTML中我们是要按顺序输出数组里的值的,所以在存的时候也要按照对应的顺序。

        1,

 for (let i=0; i<integer;i++){
          result.push(CLA_ON);
        }

存入为on的数据,

        2,

 if (hasDecimal){
          result.push(CLA_HALF)
        }

hasDecimal返回值为true/false,如果为true,则存入一个half。

        3,

 while (result.length<LENGTH){
          result.push(CLA_OFF)
        }

判断数组是否满了,不满就存入off

           例如score的值为3.7,则 integer的值是为3,hasDecimal的值为true,存入后的数组则为['on','on','on','half','off']。最后展现的则为

star组件的全部代码:

  HTML:

<template>
  <div class="star">
    <span v-for="item in itemsClass" :class="item" class="star-item">{{item}}</span>
  </div>
</template>

 js:

<script>
  const LENGTH = 5;
  const CLA_ON = 'on';
  const CLA_HALF = 'half';
  const CLA_OFF = 'off';
  export default {
    name: "star",
    props: {
      score: {
        type: Number
      }
    },
    computed: {
      itemsClass() {
        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(CLA_ON);
        }
        if (hasDecimal){
          result.push(CLA_HALF)
        }
        while (result.length<LENGTH){
          result.push(CLA_OFF)
        }
        return result;
      }
    }
  }
</script>

css:

    

<style scoped>
  .star {
    font-size: 0;
  }

  .star-item {
    width: 20px;
    height: 20px;
    margin-right: 20px;
    background-size: 20px 20px;
    display: inline-block;
    background-repeat: no-repeat;
  }

  .on {
    background-image: url("star48_on@2x.png");
  }

  .half {
    background-image: url("star48_half@2x.png");
  }

  .off {
    background-image: url("star48_off@2x.png");
  }
</style>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zeng__Y1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值