vue项目、h5项目 实现向上翻页功能--类微信聊天页面

vue项目、h5项目 实现向上翻页功能--类微信聊天信息

实现技术难点:

1:监听已经到顶部

2:加载完数据需要定位到原先位置

     -- 记录新增数据前、后的可滚动高度,

     -- 重点:移动的距离= 数据新增加载完后总高度 - 新增前总高度

如下使用vue项目:

<template>
  <div id="app">
    <div ref="container" class="container" @scroll="scroll">
      <div class="loading">加载更多...</div>
      <div v-for="(item, index) in list" :key="index" class="item">{{ item }}</div>
    </div>
  </div>
</template>

<script>

export default {
  components: {
  },
  data() {
    return {
      scrollHeight: 0,
      list: [],
      loadText: '加载中...',
      isLoading: false,
      pageSize: 20,
      pageNum: 1,
    };
  },
  mounted() {
    this.initData();

    // 首次渲染后获取scrollHeight并滑动到底部。
    this.$nextTick(() => {
      this.scrollHeight = this.$refs.container.scrollHeight;
      this.$refs.container.scrollTo({ top: this.scrollHeight });
    });
  },

  methods: {
    // 初始数据
    initData() {
      const arr = [];
      for (let i = 30; i > 0; i--) {
        arr.unshift('第' + this.pageNum + '页:' + i);
      }
      this.pageNum++;
      this.list = [...arr, ...this.list];
      this.isLoading = false;
    },
    // 滚动
    scroll(e) {
      // 滑到顶部时触发下次数据加载
      if (e.target.scrollTop == 0 && !this.isLoading) {
        this.isLoading = true;
        // 记录高度
        this.scrollHeight = this.$refs.container.scrollHeight;
        // 模拟延迟时间获取数据
        setTimeout(() => {
          this.initData();
          // 定位
          this.$nextTick(() => {
            this.$refs.container.scrollTop = this.$refs.container.scrollHeight - this.scrollHeight;
          });
        }, 2000);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 1500px;
  overflow: auto;
}
.loading{
  height: 70px;
  line-height: 70px;
  text-align: center;
}
.item {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-top: 1px solid #aaa;
}
.container .item:last-child {
  border-bottom: 1px solid #aaa;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值