【转载】Vue自定义指令实现pc端加载更多

转载来源:https://www.86886.wang/detail/5a6f19e644f9da55274c3bbd,谢谢作者分享!

原理

document.documentElement.scrollTop + document.documentElement.clientHeight >= document.documentElement.scrollHeight

只要知道什么时候滚动条到底部了,就知道了什么时间应该触发加载更多,当然有一些判断是不可少的,比如已经没有数据了,已经在加载中了就不要再次触发加载更多。

示例

<template>
  <div v-scroll="loadMore">
   <!-- 呈现你的列表数据,lists为数据,loading可以实现加载动画,noMore表示没数据了 -->
    <my-item :lists="lists" :loading="loading" :noMore="noMore" />
  </div>
</template>
<script>
import MyItem from '../components/Item.vue'
export default {
  data () {
    return {
      lists: this.$store.state.lists,
      page: 1,
      // 是否在加载中
      loading: false,
      // 请求到多少条数据
      count: '',
      // 每页多少条数据
      limit: 30,
      // 是否有更多数据
      noMore: false
    }
  },
  directives: {
    scroll: {
      bind (el, binding) {
        window.addEventListener('scroll', function () {
          let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
          if (scrollTop + document.documentElement.clientHeight >= document.documentElement.scrollHeight) {
            let loadData = binding.value
            loadData()
          }
        })
      }
    }
  },
  methods: {
    async loadMore () {
      // 没有正在加载中才会请求数据
      if (!this.loading) {
        if (this.noMore) {
          this.loading = false
          return
        }

        this.loading = true
        this.page = this.page + 1
        // 请求下一页数据
        await this.$store.dispatch('GET_LISTS', {
          page: this.page
        })

        let newData = this.$store.state.lists
        this.count = newData.length

        // 数据不够30且大于0肯定没更多数据了
        if (this.count < this.limit && this.count > 0) {
          this.noMore = true
          this.lists = this.lists.concat(newData)
          this.loading = false
        } else {
          // 数据刚好为30默认有更多数据
          this.noMore = false
          this.lists = this.lists.concat(newData)
          this.loading = false
        }
      }
    }
  },
  components: {
    MyItem
  }
}
</script>

原文地址:https://www.cnblogs.com/QMM2008/p/9636066.html