vueApp 上拉加载功能(原创)

mounted() {
      window.addEventListener('scroll', this.handleScroll, true); // 监听(绑定)滚轮滚动事件
      this.getBookList();//请求数据
},
destroyed() {
      window.removeEventListener('scroll', this.handleScroll, true); // 离开页面清除(移除)滚轮滚动事件
},
data() {
      return {
        taskList: [],
        totlePage: '',
        params: {
          page: 1,
          num: 4,
        },
        count: '',
        showTxt: '',
        flags: true,
      };
},
methods: {
      handleScroll() {
        //变量scrollTop是滚动条滚动时,距离顶部的距离
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        //变量windowHeight是可视区的高度
        var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //变量scrollHeight是滚动条的总高度
        var scrollHeight = document.documentElement.scrollHeight - 200 || document.body.scrollHeight - 200;
        //滚动条到底部的条件
        if (Math.ceil(scrollTop) + windowHeight >= scrollHeight - 200 && this.flags) {
          this.flags = false;
          this.fenye()
          //写后台加载数据的函数
          console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
        }
      },
      fenye() {
        //获取列表之后
        this.totlePage = Math.ceil(this.count / this.params.num);

        //页面触底事件
        if (this.params.page >= this.totlePage) {
          this.showTxt = '加载完成';
          return;
        }

        this.showTxt = '加载中...';
        this.params.page++;
        this.getBookList()
      },
      //获取书籍列表
      getBookList() {
        let params = {
          type: 3, //类型 1音频 2文字 3视频 4直播
          is_vip: 2, //是否为vip书籍 1否(默认) 2是
          pay_type: 2, //付费类型 1免费 2付费
          page: this.params.page,
          num: this.params.num,
        }
        this.$post("/books/book/book_list", params).then(res => {
          if (!res.error_code) {
            console.log(res.response_data, 'res')
            this.count = res.response_data.count;
            this.taskList = this.taskList.concat(res.response_data.lists); //合并数组
            this.flags = true;
          } else {
            this.$toast(res.error_msg);
            console.log(res.error_msg, 'error')
          }
        })
      },
}

 

posted @ 2020-05-12 14:25  自律·给我自由  阅读(733)  评论(0编辑  收藏  举报