【初学者笔记】数组轮询

66 阅读1分钟
  • 需求: 给一个数组列表,进行循环输出
  • 难点: 数组头尾的衔接
<script>
export default {
    created() { 
       // 截取标识,在每次请求数据的时候需要进行初始化
       this.sliceFlag = 0;
       this.sliceNum = 3; // 截取数量
       this.millisec = 2 * 60 * 1000; // 定时器时长
       this.timeout = null;
       // 轮询列表,在实际业务场景中是从后台请求回来的
       this.carouselList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
   },
  data(){
      return {
    	      monitorVideoList: [],
      };
  },
   methods: {
       queryCarouselList() {
           let length = this.carouselList.length;
           let list = [];
           if (length > this.sliceNum) {
               for (let i = 0; i < this.sliceNum; i++) {
                   //  次数       下标       输出
                   // 第一次    0, 1, 2    [1, 2, 3]
                   // 第二次    3, 4, 5    [4, 5, 6]
                   // 第三次    6, 7, 8    [7, 8, 9]
                   // 第四次    9, 10, 0   [10, 11, 1]
                   // 第五次    1, 2, 3    [2, 3, 4]
                   // ...
                   list.push(this.carouselList[(this.sliceFlag + i) % length]);
               };
               this.monitorVideoList = list;
               // 取标识数字++ 0 3 6 9 12
               this.sliceFlag = this.sliceFlag + this.sliceNum;
           } else {
               // 防止引用类型数据地址值一样
               this.monitorVideoList = [...this.carouselList];
           }
       },
       // 定时请求轮询列表
       requestInterval() {
           console.log('定时器');
           this.timeout = setTimeout(() => {
               this.requestInterval();
           }, this.millisec);
           this.queryCarouselList();
       },
},
   beforeDestroy() {
       this.timeout && clearTimeout(this.timeout);
       this.timeout = null;
   },
}
</script>

PS: 之前遇到问题,在各大平台搜索的时候,总感觉内容过于冗长,看一点就不想看了,所以就突发奇想,能不能用尽量简单的方法,简短的文字,尽可能的描述清楚问题,以及提供对应的解决方案(说白了就是比较懒~)。 前端小白,还有诸多不足,请各位大佬多多指教~

- 我们不过是宇宙里的尘埃、时间长河里的水滴 -

- 所以大胆去做不要怕,没有人在乎 -

- 就算有人在乎,人又算什么东西 -