数字滚动组件

102 阅读1分钟

使用方式: 代码如下:

<template>
  <div class="demo">
    <ul class="fp-box">
      <!-- 需要显示的列 -->
      <li ref="li" v-for="i in numColumn" :key="i">
        <!-- 每列中的10行数字 -->
        <span v-for="num in 10" :key="num">{{ num - 1 }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    column: {
      default: 6,
    },
    value: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      numColumn: this.column || 6, //显示列数
      numberArr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      numStr: this.value || "0", // 需要展示的数字字符串
      numArr: [], //默认展示数字数组
    };
  },

  watch: {
    numStr: {
      handler(newValue, oldValue) {
        setTimeout(() => {
          this.updateNum(newValue);
        }, 10);
      },
      deep: true,
      immediate:true,
    },

  },

  methods: {
    updateNum(num) {
      this.numStr = num;
      this.numArr = this.numStr.split("");
      let numArrlen = this.numArr.length;
      // 展示数字的处理 补0
      for (let i = 0; i < this.numColumn - numArrlen; i++) {
        this.numArr.unshift(0);
      }
      this.$refs.li.forEach((item, index) => {
        let ty = this.numArr[index];
        // 滚动数字(li标签)
        item.style.transform = `translateY(-${ty * 2.5}rem)`;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.fp-box {
  display: flex;
  flex-direction: row;
  overflow: hidden;
  li {
    width: 1.5rem;
    height: 2rem;
    margin-right: 0.2rem;
    flex-direction: column;
    transition: transform 1s ease-in-out;
    span {
      position: relative;
      font-size: 1rem;
      color: #ffd900;
      display: flex;
      justify-content: center;
      align-items: center;
      font-weight: bolder;
      width: 1.5rem;
      height: 2rem;
      background-color: #09856262;
      z-index: 1;
      margin-bottom: 0.5rem;
    }
    span::before {
      position: absolute;
      z-index: -1;
      content: "";
      width: 1.4rem;
      height: 1.9rem;
      // background-color: rgb(11, 91, 47);
      border: 1px solid rgba(16, 255, 175, 0.425);
    }
  }
}
</style>