列表无限滚动

<template>
  <div class="container">
    <div class="list" ref="box" @mouseenter="enter" @mouseleave="leave">
      <div class="list-item" v-for="(item, index) in list" :key="index">
        <span>我是第{{ item }}条数据</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      y: 0,
      refId: null,
    };
  },
  watch: { //滚动监听 如果滚动高度大于item高度触发
    y() {
      // 51是list-item的高度
      if (this.y !== 0 && this.y % 51 === 0) {
        window.cancelAnimationFrame(this.refId);
        this.list.push(this.list[0]);
        this.list.shift();
        this.y = 0;
        this.reqAnimationFrame();
      }
    },
  },
  mounted() {
    this.list = new Array(20).fill(1).map((v, i) => {
      return i + 1;
    });
    this.reqAnimationFrame();
  },
  beforeDestroy(){
    this.refId = null
  },
  methods: {
    enter() {
      window.cancelAnimationFrame(this.refId);
    },
    leave() {
      this.reqAnimationFrame();
    },
    reqAnimationFrame() {
      this.refId = window.requestAnimationFrame(this.reqAnimationFrame);
      this.y++;
      if (this.$refs.box) {
        this.$refs.box.style.top = `${-this.y}px`;
      }
    },
  },
};
</script>

<style scoped lang="less">
.container {
  margin: auto;
  width: 500px;
  height: 700px;
  position: relative;
  padding: 20px;
  overflow: hidden;
  border: 1px solid #666;
  .list {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    right: 0;
    .list-item {
      height: 50px;
      background-color: aqua;
      // padding: 10px 20px;
      border-bottom: 1px solid red;
    }
  }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值