滚动加载的简单实现方式

以下在vue项目中不用插件的情况下的下拉滚动加载案例

模板部分:

    <div class="listArea">
      <div class="scrollList">
        <div class="item" v-for="item in list" :key="item.id">
          <div class="circle"></div>
          <div class="info">{{item.info}}</div>
        </div>
      </div>
    </div>

js部分:

data() {
    return{
      list: [],
      api: {
        list: '/接口地址'
      },
      pageSize: 20,
      pageNo: 1
    }
  },
  mounted() {
    this.getData()
    let el = document.querySelector('.listArea')
    let that = this
    el.addEventListener('scroll', function (e) {
      let scrollTop = e.target.scrollTop;
      // 可视区高度
      let clientHeight = e.target.clientHeight;
      // 滚动条总高度
      let scrollHeight = e.target.scrollHeight;
      console.log(scrollHeight - 1, scrollTop + clientHeight);
      if (Math.ceil(scrollTop + clientHeight) >= (scrollHeight - 1) && that.total >= (that.pageSize * that.pageNo)) {
        that.pageNo++
        that.getData()
      }
    }) //监听页面滚动
  },
  destroyed() {
    let el = document.querySelector('.listArea')
    el.removeEventListener("scroll", this.windowScroll);//销毁滚动事件
  },
  methods: {
    getData() {
      //参数
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        order: 'desc',
        column: 'createTime'
      }
      //接口请求将数据展示到页面上
      getAction(this.api.list, params).then(res => {
        this.total = res.result.total
        res.result.records.forEach(item => {
          let newItem = {
            info: item.createTime + ' - ' + item.info,
            id: item.id
          }
          this.list.push(newItem)
        })
      })
    }
  },

布局方面,主要是把listArea的overflow设置成auto就行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值