基于vue2实现上拉加载功能


Posted in Javascript onNovember 28, 2017

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

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

<template>
  <div class="loadmore">
    <slot></slot>
    <slot name="bottom">
    </slot>
  </div>
</template>

<style>
  .loadmore{
    width:100%;
  }
</style>

<script>
  export default {
    name: 'loadmore',
    props: {
      maxDistance: {
        type: Number,
        default: 0
      },
      autoFill: {
        type: Boolean,
        default: true
      },
      distanceIndex: {
        type: Number,
        default: 2
      },
      bottomPullText: {
        type: String,
        default: '上拉刷新'
      },
      bottomDropText: {
        type: String,
        default: '释放更新'
      },
      bottomLoadingText: {
        type: String,
        default: '加载中...'
      },
      bottomDistance: {
        type: Number,
        default: 70
      },
      bottomMethod: {
        type: Function
      },
      bottomAllLoaded: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        // 最下面出现的div的位移
        translate: 0,
        // 选择滚动事件的监听对象
        scrollEventTarget: null,
        containerFilled: false,
        bottomText: '',
        // class类名
        bottomDropped: false,
        // 获取监听滚动元素的scrollTop
        bottomReached: false,
        // 滑动的方向  down---向下互动;up---向上滑动
        direction: '',
        startY: 0,
        startScrollTop: 0,
        // 实时的clientY位置
        currentY: 0,
        topStatus: '',
        // 上拉加载的状态  ''   pull: 上拉中
        bottomStatus: '',
      };
    },
    watch: {
      // 改变当前加载在状态
      bottomStatus(val) {
        this.$emit('bottom-status-change', val);
        switch (val) {
          case 'pull':
            this.bottomText = this.bottomPullText;
            break;
          case 'drop':
            this.bottomText = this.bottomDropText;
            break;
          case 'loading':
            this.bottomText = this.bottomLoadingText;
            break;
        }
      }
    },
    methods: {
      onBottomLoaded() {
        this.bottomStatus = 'pull';
        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 !== 'HTML' &&
        currentNode.tagName !== 'BODY' && currentNode.nodeType === 1) {
          let overflowY = document.defaultView.getComputedStyle(currentNode).overflowY;
          if (overflowY === 'scroll' || overflowY === 'auto') {
            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('touchstart', this.handleTouchStart);
        this.$el.addEventListener('touchmove', this.handleTouchMove);
        this.$el.addEventListener('touchend', this.handleTouchEnd);
      },
      init() {
        this.bottomStatus = 'pull';
        // 选择滚动事件的监听对象
        this.scrollEventTarget = this.getScrollEventTarget(this.$el);
        if (typeof this.bottomMethod === 'function') {
          // 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 = 'loading';
            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 !== 'loading') {
          this.bottomStatus = 'pull';
          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 ? 'down' : 'up';
        if (this.direction === 'up') {
          // 获取监听滚动元素的scrollTop
          this.bottomReached = this.bottomReached || this.checkBottomReached();
        }
        if (typeof this.bottomMethod === 'function' && this.direction === 'up' &&
            this.bottomReached && this.bottomStatus !== 'loading' && !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 ? 'drop' : 'pull';
        }
      },
      // ontouchend事件
      handleTouchEnd() {
        if (this.direction === 'up' && this.bottomReached && this.translate < 0) {
          this.bottomDropped = true;
          this.bottomReached = false;
          if (this.bottomStatus === 'drop') {
            this.translate = '-50';
            this.bottomStatus = 'loading';
            this.bottomMethod();
          } else {
            this.translate = '0';
            this.bottomStatus = 'pull';
          }
        }
        this.direction = '';
      }
    },
    mounted() {
      this.init();
    }
  };
</script>

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

<template>
 <section class="finan">
  <!-- 上拉加载更多 -->
  <load-more
  :bottom-method="loadBottom"
  :bottom-all-loaded="allLoaded"
  :bottomPullText='bottomText'
  :auto-fill="false"
  @bottom-status-change="handleBottomChange"
  ref="loadmore">
    <div>
  这里写你需要的另外的模块
    </div>
    <div v-show="loading" slot="bottom" class="loading"> 这个div是为让上拉加载的时候显示一张加载的gif图
     <img src="./../../assets/main/uploading.gif">
    </div>
  </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;
    },
  }

这样就完成了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
使用JavaScript库还是自己写代码?
Jan 28 Javascript
jquery select动态加载选择(兼容各种浏览器)
Feb 01 Javascript
js设置和获取自定义属性的方法
Oct 20 Javascript
input file上传 图片预览功能实例代码
Oct 25 Javascript
清除输入框内的空格
Dec 21 Javascript
js通过keyCode值判断单击键盘上某个键,然后触发指定的事件方法
Feb 19 Javascript
jQuery复合事件用法示例
Jun 10 jQuery
Vue 与 Vuex 的第一次接触遇到的坑
Aug 16 Javascript
element-ui使用导航栏跳转路由的用法详解
Aug 22 Javascript
JS/jQuery实现超简单的Table表格添加,删除行功能示例
Jul 31 jQuery
js实现贪吃蛇小游戏(加墙)
Jul 31 Javascript
简单聊聊Vue中的计算属性和属性侦听
Oct 05 Vue.js
微信小程序模板和模块化用法实例分析
Nov 28 #Javascript
基于Vue的移动端图片裁剪组件功能
Nov 28 #Javascript
javaScript canvas实现(画笔大小 颜色 橡皮的实例)
Nov 28 #Javascript
基于Vue框架vux组件库实现上拉刷新功能
Nov 28 #Javascript
JavaScript中关于class的调用方法
Nov 28 #Javascript
基于vue+canvas的excel-like组件实例详解
Nov 28 #Javascript
JS原型继承四步曲及原型继承图一览
Nov 28 #Javascript
You might like
全国FM电台频率大全 - 25 云南省
2020/03/11 无线电
自制短波长线天线频率预选器 - 成功消除B2K之流的镜像
2021/03/02 无线电
php 下载保存文件保存到本地的两种实现方法
2013/08/12 PHP
php Imagick获取图片RGB颜色值
2014/07/28 PHP
Symfony2安装的方法(2种方法)
2016/02/04 PHP
完美利用Yii2微信后台开发的系列总结
2016/07/18 PHP
PHP Oauth授权和本地加密实现方法
2016/08/12 PHP
PHP针对伪静态的注入总结【附asp与Python相关代码】
2017/08/01 PHP
TinyMCE 新增本地图片上传功能
2010/11/05 Javascript
JS实现判断滚动条滚到页面底部并执行事件的方法
2014/12/18 Javascript
Node.js connect ECONNREFUSED错误解决办法
2016/09/15 Javascript
jQuery点击弹出层弹出模态框点击模态框消失代码分享
2017/01/21 Javascript
js+html5实现页面可刷新的倒计时效果
2017/07/15 Javascript
js移动端事件基础及常用事件库详解
2017/08/15 Javascript
Jquery实现无缝向上循环滚动列表的特效
2019/02/13 jQuery
详解Python中dict与set的使用
2015/08/10 Python
浅谈Python单向链表的实现
2015/12/24 Python
Python3连接SQLServer、Oracle、MySql的方法
2018/06/28 Python
python程序中的线程操作 concurrent模块使用详解
2019/09/23 Python
Django扫码抽奖平台的配置过程详解
2021/01/14 Python
python的scipy.stats模块中正态分布常用函数总结
2021/02/19 Python
印度在线杂货店:bigbasket
2018/08/23 全球购物
Brasty罗马尼亚:购买手表、香水、化妆品、珠宝
2020/04/21 全球购物
初中体育教学反思
2014/01/14 职场文书
优秀教师的感人事迹
2014/02/04 职场文书
同事打架检讨书
2014/02/04 职场文书
《浅水洼里的小鱼》听课反思
2014/02/28 职场文书
推普周国旗下讲话稿
2014/09/21 职场文书
公司股份合作协议书
2014/12/07 职场文书
同学聚会通知书
2015/04/20 职场文书
硕士论文致谢范文
2015/05/14 职场文书
色戒观后感
2015/06/12 职场文书
工作服管理制度范本
2015/08/06 职场文书
少先队大队委竞选口号
2015/12/25 职场文书
2016党员发展对象培训心得体会
2016/01/08 职场文书
HTML+CSS 实现顶部导航栏菜单制作
2021/06/03 HTML / CSS