封装scroll数字滚动组件

278 阅读1分钟

一、封装scroll数字滚动组件

<template>
  <div class="numberBox">
    <div
      :class="{ itemBox: !isNaN(item), comma: isNaN(item) }"
      v-for="(item, index) in orderNum"
      :key="index"
    >
      <div class="numBoxItem" v-if="!isNaN(item)">
        <div style="transition: transform 0.5s ease-in-out" ref="numberItem">
          <div class="numcount">0</div>
          <div class="numcount">1</div>
          <div class="numcount">2</div>
          <div class="numcount">3</div>
          <div class="numcount">4</div>
          <div class="numcount">5</div>
          <div class="numcount">6</div>
          <div class="numcount">7</div>
          <div class="numcount">8</div>
          <div class="numcount">9</div>
        </div>
      </div>
      <!-- 加点隔开 -->
      <!-- <span v-else>{{ item }}</span> -->
    </div>
  </div>
</template>

<script>
export default {
  props: {
    number: {
      type: Number,
    },
  },
  watch: {
    number(val) {
      let vm = this;
      vm.toOrderNum(val);
      vm.setNumberTransform();
    },
  },
  data() {
    return {
      orderNum: ["0", "0", ",", "0", "0", "0", ",", "0", "0", "0"],
    };
  },
  methods: {
    // 不足8位的数字前面补0
    toOrderNum(num) {
      let vm = this;
      num = num.toString();
      if (num.length < 8) {
        num = "0" + num;
        vm.toOrderNum(num);
      } else if (num.length === 8) {
        num = num.slice(0, 2) + "," + num.slice(2, 5) + "," + num.slice(5, 8);
        vm.orderNum = num.split("");
      } else {
        this.$message.warning("数字长度不能超过8位");
      }
    },
    // 设置文字滚动
    setNumberTransform() {
      let vm = this;
      let numberItems = vm.$refs.numberItem;
      let numberArr = vm.orderNum.filter((item) => !isNaN(item));
      for (let index = 0; index < numberItems.length; index++) {
        let elem = numberItems[index];
        elem.style.transform = `translateY(-${numberArr[index] * 10}%)`;
      }
    },
  },
  mounted() {
    let vm = this;
    vm.toOrderNum(vm.number);
    vm.setNumberTransform();
  },
};
</script>

<style lang="scss">
.numberBox {
  height: 2rem;
  display: flex;
  overflow: hidden;
  color: #fff;
  .itemBox {
    position: relative;
    display: inline-block;
    width: 1.5rem;
    height: 2rem;
    background: url("../assets/images/numberBack.png") no-repeat center center;
    background-size: 100% 100%;
    font-size: 1.5rem;
    line-height: 2rem;
    text-align: center;
    margin-right: 0.1rem;
    .itemBox .numBoxItem {
      position: absolute;
      top: 0;
      left: 0;
      display: block;
      width: 1.5rem;
    }
  }
  // .comma {
  //     width: 10px;
  //     height: 52px;
  //     font-size: 34px;
  //     position: relative;
  //     margin-right: 5px;
  //     span {
  //         position: absolute;
  //         width: 100%;
  //         bottom: 0;
  //     }
  // }
}
</style>