一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Vue实现分批加载数据代码示例

时间:2022-04-11 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Vue实现分批加载数据代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

首先我们需要定义四个全局的变量

pagindex页码

pagesize一页要请求多少条数据

pagetotal一共要请求多少次(总数 / pagesize),总是是后台返回的~

intertimer存的定时器的函数,方便清除定时器

export default {
  name: "map_app",
  inject:['reload'],
  data() {
    return {
      pagindex: 1, //页码
      pagesize: 300, //页/条数
      pagetotal: 0, //一共要请求的次数
      intertimer: null, //定时器
     }
   }
}

然后再methods中写定时器 让定时器每隔三秒再去执行一个方法;

//定时器
getPageInter(map) {
  this.loading = this.$loading({ //加载层
        lock: true,
        text: "拼命加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
    });
 
    this.intertimer = setInterval(() => {
       this.intervalData(map); //每三秒调用一次方法
      }, 3000);
 },

然后再这个方法里面我们去做判断,如果当前请求的页数超过一共要请求的次数就清楚定时器!

//定时器2
intervalData(map) {
   if (this.pagindex > this.pagetotal) {
        clearInterval(this.intertimer); //关闭定时器
        this.loading.close(); //关闭弹窗
        this.pagindex = 1;
    } else {
        this.renderMesh(map); //数据渲染
        this.pagindex += 1;
      }
},

总数是后台小哥哥返回的,然后我们每次去请求接口的时候要给后台传当前是第几页,还有要请求多少条数据

renderMesh(map) { 
     this.$axios
       .get(this.httpApi + "/api/Main/GetBlockMap", {
          params: {
            BlockCode: this.pageid,
            page: this.pagindex, //当前页码
            rownum: this.pagesize //请求数量
          }
      })
      .then(res => {
       console.log(res);
      })
      .catch(err => {
       console.log("请求失败233");
       });
}

因为总数是调用的另外一个接口,然后也写一下代码

    this.$axios
    .get(this.httpApi + "/api/Main/GetBlockMapCount", {
          params: {
            BlockCode: this.pageid
          }
     })
     .then(res => {
          let jsonData = eval("(" + res.data + ")");
          //总数除每次请求多少条数据得出一共要请求多少次
          this.pagetotal = Math.ceil(jsonData.totals / this.pagesize); 
      })
      .catch(err => {
          console.log("请求失败");
      });

滚动加载数据

核心方法:

handleScroll: function () {
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      var windowHeitht =
        document.documentElement.clientHeight || document.body.clientHeight;
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      if (scrollTop + windowHeitht >= scrollHeight - 2000) {
        if (this.scroll) {
          this.GetSpecialData();
        }
      }
    },
    GetSpecialData() {
      this.scroll = false;
      this.page.pageIndex++;
      this.load(this.page, this.query);
    },

监听:

 mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll, false);
  },

热门栏目