在vue2中如何实现上拉加载功能

亚连

亚连

2018-06-23

2436人浏览

原创

这篇文章主要为大家详细介绍了基于vue2实现上拉加载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了vue2实现上拉加载展示的具体代码,供大家参考,具体内容如下

因为我们项目中,还用了swiper。很多都是滑动切换的,但是又得上拉加载,所以导致,很多UI框架,我们用了,都有不同的bug出现,没办法,最后写了一个。代码如下(这个因为很多地方会用,所以建议放在components/common下面):

<template>
  <p>
    <slot></slot>
    <slot>
    </slot>
  </p>
</template><style>
  .loadmore{
    width:100%;
  }
</style><script>
  export default {
    name: &#39;loadmore&#39;,
    props: {
      maxDistance: {
        type: Number,
        default: 0
      },
      autoFill: {
        type: Boolean,
        default: true
      },
      distanceIndex: {
        type: Number,
        default: 2
      },
      bottomPullText: {
        type: String,
        default: &#39;上拉刷新&#39;
      },
      bottomDropText: {
        type: String,
        default: &#39;释放更新&#39;
      },
      bottomLoadingText: {
        type: String,
        default: &#39;加载中...&#39;
      },
      bottomDistance: {
        type: Number,
        default: 70
      },
      bottomMethod: {
        type: Function
      },
      bottomAllLoaded: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        // 最下面出现的p的位移
        translate: 0,
        // 选择滚动事件的监听对象
        scrollEventTarget: null,
        containerFilled: false,
        bottomText: &#39;&#39;,
        // class类名
        bottomDropped: false,
        // 获取监听滚动元素的scrollTop
        bottomReached: false,
        // 滑动的方向  down---向下互动;up---向上滑动
        direction: &#39;&#39;,
        startY: 0,
        startScrollTop: 0,
        // 实时的clientY位置
        currentY: 0,
        topStatus: &#39;&#39;,
        // 上拉加载的状态  &#39;&#39;   pull: 上拉中
        bottomStatus: &#39;&#39;,
      };
    },
    watch: {
      // 改变当前加载在状态
      bottomStatus(val) {
        this.$emit(&#39;bottom-status-change&#39;, val);
        switch (val) {
          case &#39;pull&#39;:
            this.bottomText = this.bottomPullText;
            break;
          case &#39;drop&#39;:
            this.bottomText = this.bottomDropText;
            break;
          case &#39;loading&#39;:
            this.bottomText = this.bottomLoadingText;
            break;
        }
      }
    },
    methods: {
      onBottomLoaded() {
        this.bottomStatus = &#39;pull&#39;;
        this.bottomDropped = false;
        this.$nextTick(() => {
          if (this.scrollEventTarget === window) {
          document.body.scrollTop += 50;
        } else {
          this.scrollEventTarget.scrollTop += 50;
        }
        this.translate = 0;
      });
        // 注释
        if (!this.bottomAllLoaded && !this.containerFilled) {
          this.fillContainer();
        }
      },

      getScrollEventTarget(element) {
        let currentNode = element;
        while (currentNode && currentNode.tagName !== &#39;HTML&#39; &&
        currentNode.tagName !== &#39;BODY&#39; && currentNode.nodeType === 1) {
          let overflowY = document.defaultView.getComputedStyle(currentNode).overflowY;
          if (overflowY === &#39;scroll&#39; || overflowY === &#39;auto&#39;) {
            return currentNode;
          }
          currentNode = currentNode.parentNode;
        }
        return window;
      },
      // 获取scrollTop
      getScrollTop(element) {
        if (element === window) {
          return Math.max(window.pageYOffset || 0, document.documentElement.scrollTop);
        } else {
          return element.scrollTop;
        }
      },
      bindTouchEvents() {
        this.$el.addEventListener(&#39;touchstart&#39;, this.handleTouchStart);
        this.$el.addEventListener(&#39;touchmove&#39;, this.handleTouchMove);
        this.$el.addEventListener(&#39;touchend&#39;, this.handleTouchEnd);
      },
      init() {
        this.bottomStatus = &#39;pull&#39;;
        // 选择滚动事件的监听对象
        this.scrollEventTarget = this.getScrollEventTarget(this.$el);
        if (typeof this.bottomMethod === &#39;function&#39;) {
          // autoFill 属性的实现  注释
          this.fillContainer();
          // 绑定滑动事件
          this.bindTouchEvents();
        }
      },
      // autoFill 属性的实现  注释
      fillContainer() {
        if (this.autoFill) {
          this.$nextTick(() => {
            if (this.scrollEventTarget === window) {
            this.containerFilled = this.$el.getBoundingClientRect().bottom >=
                document.documentElement.getBoundingClientRect().bottom;
          } else {
            this.containerFilled = this.$el.getBoundingClientRect().bottom >=
                this.scrollEventTarget.getBoundingClientRect().bottom;
          }
          if (!this.containerFilled) {
            this.bottomStatus = &#39;loading&#39;;
            this.bottomMethod();
          }
        });
        }
      },
      // 获取监听滚动元素的scrollTop
      checkBottomReached() {
        if (this.scrollEventTarget === window) {
          return document.body.scrollTop + document.documentElement.clientHeight >= document.body.scrollHeight;
        } else {
          // getBoundingClientRect用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。 right是指元素右边界距窗口最左边的距离,bottom是指元素下边界距窗口最上面的距离。
          return this.$el.getBoundingClientRect().bottom <= this.scrollEventTarget.getBoundingClientRect().bottom + 1;
        }
      },
      // ontouchstart 事件
      handleTouchStart(event) {
        // 获取起点的y坐标
        this.startY = event.touches[0].clientY;
        this.startScrollTop = this.getScrollTop(this.scrollEventTarget);
        this.bottomReached = false;
        if (this.bottomStatus !== &#39;loading&#39;) {
          this.bottomStatus = &#39;pull&#39;;
          this.bottomDropped = false;
        }
      },
      // ontouchmove事件
      handleTouchMove(event) {
        if (this.startY < this.$el.getBoundingClientRect().top && this.startY > this.$el.getBoundingClientRect().bottom) {
          // 没有在需要滚动的范围内滚动,不再监听scroll
          return;
        }
        // 实时的clientY位置
        this.currentY = event.touches[0].clientY;
        // distance 移动位置和开始位置的差值    distanceIndex---
        let distance = (this.currentY - this.startY) / this.distanceIndex;
        // 根据 distance 判断滑动的方向 并赋予变量  direction down---向下互动;up---向上滑动
        this.direction = distance > 0 ? &#39;down&#39; : &#39;up&#39;;
        if (this.direction === &#39;up&#39;) {
          // 获取监听滚动元素的scrollTop
          this.bottomReached = this.bottomReached || this.checkBottomReached();
        }
        if (typeof this.bottomMethod === &#39;function&#39; && this.direction === &#39;up&#39; &&
            this.bottomReached && this.bottomStatus !== &#39;loading&#39; && !this.bottomAllLoaded) {
          // 有加载函数,是向上拉,有滚动距离,不是正在加载ajax,没有加载到最后一页
          event.preventDefault();
          event.stopPropagation();
          if (this.maxDistance > 0) {
            this.translate = Math.abs(distance) <= this.maxDistance
                ? this.getScrollTop(this.scrollEventTarget) - this.startScrollTop + distance : this.translate;
          } else {
            this.translate = this.getScrollTop(this.scrollEventTarget) - this.startScrollTop + distance;
          }
          if (this.translate > 0) {
            this.translate = 0;
          }
          this.bottomStatus = -this.translate >= this.bottomDistance ? &#39;drop&#39; : &#39;pull&#39;;
        }
      },
      // ontouchend事件
      handleTouchEnd() {
        if (this.direction === &#39;up&#39; && this.bottomReached && this.translate < 0) {
          this.bottomDropped = true;
          this.bottomReached = false;
          if (this.bottomStatus === &#39;drop&#39;) {
            this.translate = &#39;-50&#39;;
            this.bottomStatus = &#39;loading&#39;;
            this.bottomMethod();
          } else {
            this.translate = &#39;0&#39;;
            this.bottomStatus = &#39;pull&#39;;
          }
        }
        this.direction = &#39;&#39;;
      }
    },
    mounted() {
      this.init();
    }
  };
</script>

然后哪个页面需要,在哪个页面导入即可:import LoadMore from './../common/loadmore.vue';在需要引入他的页面写法如下:

<template>
 <section>
  <!-- 上拉加载更多 -->
  <load-more>
    <p>
  这里写你需要的另外的模块
    </p>
    <p> 这个p是为让上拉加载的时候显示一张加载的gif图
     @@##@@
    </p>
  </load-more>
 </section></template>

然后在此页面的data里和methods设置如下:

  export default {
    name: 'FinancialGroup',
    props:{
 
    },
    data () {
      return {
        // 上拉加载数据
        scrollHeight: 0,
        scrollTop: 0,
        containerHeight: 0,
        loading: false,
        allLoaded: false,
        bottomText: '上拉加载更多...',
        bottomStatus: '',
        pageNo: 1,
        totalCount: '',
      }
    },
    methods: {
    /* 下拉加载 */
    _scroll: function(ev) {
      ev = ev || event;
      this.scrollHeight = this.$refs.innerScroll.scrollHeight;
      this.scrollTop = this.$refs.innerScroll.scrollTop;
      this.containerHeight = this.$refs.innerScroll.offsetHeight;
    },
    loadBottom: function() {
      this.loading = true;
      this.pageNo += 1;  // 每次更迭加载的页数
      if (this.pageNo == this.totalGetCount) {
        // 当allLoaded = true时上拉加载停止
        this.loading = false;
        this.allLoaded = true;
      }
      api.commonApi(后台接口,请求参数) 这个api是封装的axios有不懂的可以看vue2+vuex+axios那篇文章
          .then(res => {
        setTimeout(() => {
      要使用的后台返回的数据写在setTimeout里面
         this.$nextTick(() => {
          this.loading = false;
        })
      }, 1000)
     });
    },
    handleBottomChange(status) {
      this.bottomStatus = status;
    },
  }

上面是我整理给大家的,希望今后会对大家有帮助。

Vue-router参考手册
Vue-router参考手册

Vue-router参考手册下载

下载

相关文章:

使用JavaScript如何实现寄生组合式继承

在JS中如何实现非首屏图片延迟加载

在jQuery中有关于库的引用方法有哪些

在js中如何生成word图片

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

vue

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
墨刀AI提示词教学
墨刀AI提示词教学

本合集由PHP中文网精心整理,为您提供全面的墨刀AI提示词教学。内容涵盖高质量原型撰写公式与实操窍门,助您轻松掌握AI设计工具。无论是零基础入门还是进阶技巧,都能让您快速上手,大幅提升产品设计与协作效率。

2026.08.04

9

21

墨刀AI完整入门
墨刀AI完整入门

PHP中文网为您倾力打造墨刀AI保姆级入门指南完整版!本合集从零基础讲起,涵盖AI生成原型、提示词优化、图片转原型及多轮对话等核心功能。无论您是新手还是进阶用户,都能轻松掌握产品设计全流程。快来PHP中文网,一键解锁高效设计技巧,让想法即刻成型!

2026.08.04

7

20

墨刀AI进阶技巧
墨刀AI进阶技巧

本合集由PHP中文网精心整理,为您提供墨刀AI核心进阶策略指南。内容涵盖高效提示词写作、原型智能生成与微调、结构化导图制作及行业分析报告输出等实战技巧。助您轻松掌握AI设计工具,大幅提升产品设计与团队协作效率。

2026.08.04

8

14

火山引擎实名认证失败怎么办
火山引擎实名认证失败怎么办

火山引擎实名认证失败可能与证件信息填写错误、姓名或企业信息不一致、证件照片不清晰、营业执照状态异常、手机号验证失败或审核资料不完整有关。本专题整理个人认证、企业认证、资料上传、审核退回、重新提交和认证不通过的常见处理方法。

2026.08.04

4

10

火山引擎域名备案流程详解
火山引擎域名备案流程详解

火山引擎域名备案适合需要在火山引擎云服务器、对象存储、CDN或网站服务上绑定域名的用户参考。本专题整理备案入口、账号实名认证、备案类型选择、主体信息填写、网站信息提交、资料上传、初审核验、管局审核和备案失败排查,帮助用户完成网站上线前的备案流程。

2026.08.04

1

10

火山引擎DNS解析配置步骤
火山引擎DNS解析配置步骤

使用火山引擎DNS解析网站域名时,需要确认域名已完成管理接入,并正确配置服务器IP、CNAME地址或验证记录。本专题整理域名添加、记录类型选择、TTL设置、解析状态检查、备案和访问测试等流程,适合新手搭建网站时参考。

2026.08.04

3

10

火山引擎对象存储使用教程
火山引擎对象存储使用教程

火山引擎对象存储适合用于网站图片、视频文件、备份数据、静态资源和应用附件管理。本专题整理TOS控制台入口、存储桶创建、地域选择、权限设置、文件上传、访问链接生成、CDN加速、费用查看和常见上传或访问失败问题,帮助用户快速掌握对象存储基础操作。

2026.08.04

1

10

火山引擎云服务器使用教程
火山引擎云服务器使用教程

火山引擎云服务器使用教程适合第一次购买、部署和管理云服务器的用户参考。本专题整理控制台入口、实例创建、地域和配置选择、系统镜像设置、安全组放行、远程连接、网站部署、续费计费和常见连接失败问题,帮助用户快速完成云服务器基础使用流程。

2026.08.04

5

10

火山引擎API Key绑定大模型教程
火山引擎API Key绑定大模型教程

火山引擎API Key怎么绑定大模型适合需要在火山方舟、应用后台、脚本工具或AI编程软件中调用模型的开发者参考。本专题整理控制台服务开通、API Key创建、模型权限检查、模型ID选择、Base URL填写、调用测试和鉴权失败排查,帮助用户完成从密钥到模型调用的配置流程。

2026.08.04

2

10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
uni-app快速上手
uni-app快速上手

共0课时 | 0人学习

Vue 教程
Vue 教程

共42课时 | 15.6万人学习

Vue3.x 工具篇--十天技能课堂
Vue3.x 工具篇--十天技能课堂

共26课时 | 2.2万人学习