触底加载更多(原理+vue)

6,440 阅读1分钟

触底加载更多(原理)

理解

1.使用api分别获取

滚动高度(document.documentElement.scrollTop)
可视区域/屏幕高度(document.documentElement.clientHeight)
页面高度(document.documentElement.scrollHeight

2.原理 :

If(滚动高度 + 可视区域  >= 页面高度){ do something函数}  

vue中的应用

1.用事件监听,监听你要执行的事件

   window.addEventListener(‘scroll’, 你要执行的事件)

2.取消事件监听,监听你要执行的事件

   window.removeEventListener(‘scroll’, 你要执行的事件,false)

一定要取消事件监听!不然你执行完这个事件它也会到其他页面继续执行这个事件(控制台报错)。

例子

<template>
  <div class="singer-container">
    <h1 class="singer-title">歌手列表</h1>
    <ul class="singer-list clearfix">
      <li class="singer-item" v-for="(item, index) in singerList" :key="index">
        <a href="#" class="">
          <div class="singer-info">
            <img :src="`${item.picUrl}?param=180y180`">
            <span>{{item.name}}</span>
          </div>
        </a>
      </li>
    </ul>
    <div v-if ='isShow'>已经到底了</div>
  </div>
</template>

export default {
  name: 'Singer',
  data () {
    return {
      singerList: [],
      offset: 0,
      isShow: false
    }
  },
  methods: {
    getSingerList () {
      this.$api.getSinger({
        limit: 20,
        offset: this.offset
      }).then(res => {
        if (res.artists.length === 0) {
          // 显示已经到底了
          this.isShow = true
          return
        }
        // 偏移量
        this.offset += 20
        // 合并结果
        this.singerList = [...this.singerList, ...res.artists]
      })
    },
    // 触底触发函数
    listenBottomOut () {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      const clientHeight = document.documentElement.clientHeight
      const scrollHeight = document.documentElement.scrollHeight
      if (scrollTop + clientHeight >= scrollHeight) {
      	// 没有数据后,不触发请求
      	if (!isShow) {
        	this.getSingerList()
        }
        return
      }
    }
  },
  created () {
 	// 预先加载一遍
    this.getSingerList()
  },
  mounted () {
  	// 事件监听
    window.addEventListener('scroll', this.listenBottomOut)
  },
  destroyed () {
    // 离开页面取消监听
    window.removeEventListener('scroll', this.listenBottomOut, false)
  }
}

参考原文: blog.csdn.net/weixin_4633…