列表无限滚动

Vue组件实现动态滚动列表效果

<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>

在Vue.js中,列表无限滚动(Infinite Scroll)是一种常见的交互设计,用于加载更多数据直到达到用户界面的底部。当用户滚动列表的某个位置,如接近底部,Vue组件会自动触发一个事件或者方法,比如`scroll`事件或者自定义的`loadMore`方法,请求服务器获取更多的数据并更新视图。 以下是实现列表无限滚动的基本步骤: 1. **设置边界条件**:你需要跟踪已加载的数据和用户当前滚动的位置。当滚动到底部时(例如,滚动条距离底部的距离小于某个阈值),触发加载更多操作。 ```javascript mounted() { this.loadMore(); }, watch: { 'listBottom': 'loadMore', }, methods: { loadMore() { if (this.listBottom) { // 当滚动到底部时... this.fetchMoreData(); // 请求更多数据 } }, fetchMoreData() { this.loading = true; // 显示加载状态 axios.get('/api/more-data') .then(response => { this.data.push(...response.data); // 添加新数据到列表 this.listBottom = false; // 清除边界条件以便继续加载 this.loading = false; }) .catch(error => { console.error('Error fetching more data:', error); }); } } ``` 2. **处理分页或懒加载**:如果后端支持分页,你可以直接请求下一页;如果采用懒加载(即只在需要时才加载),则需要记录哪些数据已经加载。 3. **优化用户体验**:为了防止不必要的请求,可以添加延迟加载,比如先暂停几秒再请求新数据,或者设置一个滑动速度检测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值