zoukankan      html  css  js  c++  java
  • 【转载】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>
    
    
  • 相关阅读:
    c#多线程
    把.NET程序部署到没有安装.NET Framwork的机器上
    Java字符编码转换过程说明
    Window 消息大全使用详解
    Regsvr32
    VC++的应用程序框架中各类之间的访问方法
    java接收中文输入并正常显示
    Visual C#中的数据绑定
    截取系统 API 调用(转)
    几个操作文件的API函数
  • 原文地址:https://www.cnblogs.com/QMM2008/p/9636066.html
Copyright © 2011-2022 走看看