首頁  >  文章  >  web前端  >  vue mint-ui中loadmore元件解析

vue mint-ui中loadmore元件解析

小云云
小云云原創
2018-01-25 10:33:032344瀏覽

本文主要介紹了vue mint-ui源碼解析之loadmore元件,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

存取

官方存取文件mint-ui loadmore文件

##存取使用Example

html


<p id="app">
  <mt-loadmore :top-method="loadTop" :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" :max-distance="150"
         @top-status-change="handleTopChange" ref="loadmore">

    <p slot="top" class="mint-loadmore-top">
      <span v-show="topStatus === &#39;pull&#39;" :class="{ &#39;rotate&#39;: topStatus === &#39;drop&#39; }">↓</span>
      <span v-show="topStatus === &#39;loading&#39;">Loading...</span>
      <span v-show="topStatus === &#39;drop&#39;">释放更新</span>
    </p>

    <ul class="scroll-wrapper">
      <li v-for="item in list" @click="itemClick(item)">{{ item }}</li>
    </ul>

  </mt-loadmore>
</p>

css


#

<link rel="stylesheet" href="https://unpkg.com/mint-ui/lib/style.css" rel="external nofollow" >
*{
  margin: 0;
  padding: 0;
}
html, body{
  height: 100%;
}

#app{

  height: 100%;
  overflow: scroll;
}
.scroll-wrapper{
  margin: 0;
  padding: 0;
  list-style: none;

}
.scroll-wrapper li{
  line-height: 120px;
  font-size: 60px;
  text-align: center;
}

js 


##

<!-- 先引入 Vue -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/mint-ui/lib/index.js"></script>
<script>
  new Vue({
    el: &#39;#app&#39;,
    data: {
      list: [],
      allLoaded: false,
      topStatus: &#39;&#39;
    },
    created: function () {
      var i =0, len=20;
      for (; i< len; i++){
        this.list.push(&#39;demo&#39; + i);
      }

    },
    methods: {
      loadTop: function () { // 刷新数据的操作
        var self = this;
        setTimeout(function () {
          self.list.splice(0, self.list.length);
          var i =0, len=20;
          for (; i< len; i++){
            self.list.push(&#39;demo&#39; + i);
          }
          self.$refs.loadmore.onTopLoaded();
        }, 2000);
      },
      loadBottom: function () { // 加载更多数据的操作
        //load data

        //this.allLoaded = true;// 若数据已全部获取完毕
        var self = this;
        setTimeout(function () {
          var i =0; len = 10;
          for (; i< len; i++){
            self.list.push(&#39;dddd&#39; + i);
          }
          self.$refs.loadmore.onBottomLoaded();
        }, 2000);

      },
      handleTopChange: function (status) {
        this.topStatus = status;
      },
      itemClick: function (data) {
        console.log(&#39;item click, msg : &#39; + data);
      }
    }
  });
</script>

實作原理解析

佈局原則

    #loadmore元件內部由三個slot組成,分別為name=top,name=bottom, default;
  • top用來展示下拉刷新不同狀態展示的內容,初始設定margin-top為-top的高度來將自己隱藏
  • bottom同top,用於展示上拉加載更多不同狀態展示的內容
  • default填充滾動詳細內容

# #實作原理

  • 主要是透過js的touch事件的監聽來實現

  • 在touchmove事件,如果是向下滑動且滾動的dom的scrollTop為0,那麼整個元件向下偏移(滑動的距離/比值)顯示出top solt的內容

  • 在touchmove時間,如果是向上滑動並且滑動到了底部,再繼續滑動整個元件向上偏移(滑動的距離/比值)展示出bottom solt的內容

##原始碼解析

元件的template html


 <p class="mint-loadmore">
  <p class="mint-loadmore-content" :class="{ &#39;is-dropped&#39;: topDropped || bottomDropped}" :style="{ &#39;transform&#39;: &#39;translate3d(0, &#39; + translate + &#39;px, 0)&#39; }">
   <slot name="top">
    <p class="mint-loadmore-top" v-if="topMethod">
     <spinner v-if="topStatus === &#39;loading&#39;" class="mint-loadmore-spinner" :size="20" type="fading-circle"></spinner>
     <span class="mint-loadmore-text">{{ topText }}</span>
    </p>
   </slot>
   <slot></slot>
   <slot name="bottom">
    <p class="mint-loadmore-bottom" v-if="bottomMethod">
     <spinner v-if="bottomStatus === &#39;loading&#39;" class="mint-loadmore-spinner" :size="20" type="fading-circle"></spinner>
     <span class="mint-loadmore-text">{{ bottomText }}</span>
    </p>
   </slot>
  </p>
 </p>

關於上面的spinner標籤,是一個元件,這裡不做詳細介紹。 top solt和bottom slot的內容是展示的內容,可以透過外部自訂的方式傳入。


其實它的實作有一個很嚴重的弊端,就是寫死了top solt和bottom slot的高度為50px,而且js中的處理也是使用50px進行的邏輯處理。所以並滿足我們在開發中自訂top slot 和bottom slot的需求。

js核心解析

  • props解析:關於props的解析,可以參考mint-ui的官方文件

  • ##data解析

data() {
 return {
  translate: 0, // 此变量决定当前组件上下移动,
  scrollEventTarget: null, // 滚动的dom节点
  containerFilled: false, // 当前滚动的内容是否填充完整,不完成会调用 loadmore的回调函数
  topText: &#39;&#39;, // 下拉刷新,显示的文本
  topDropped: false, // 记录当前drop状态,用给组件dom添加is-dropped class(添加回到原点的动画)
  bottomText: &#39;&#39;, // 上拉加载更多 显示的文本
  bottomDropped: false, // 同topDropped
  bottomReached: false, // 当前滚动是否滚动到了底部
  direction: &#39;&#39;, // touch-move过程中, 当前滑动的方向
  startY: 0, // touch-start 起始的y的坐标值
  startScrollTop: 0, // touch-start 起始的滚动dom的 scrollTop
  currentY: 0, // touch-move 过程中的 y的坐标
  topStatus: &#39;&#39;, // 下拉刷新的状态: pull(下拉) drop(释放) loading(正在加载数据)
  bottomStatus: &#39;&#39; // 上拉加载更多的状态: 状态同上
 };
}

上面的關於每個data資料的具體作用透過註解做了詳細說明。

watch解析

watch: {
 topStatus(val) {
  this.$emit(&#39;top-status-change&#39;, val);
  switch (val) {
   case &#39;pull&#39;:
    this.topText = this.topPullText;
    break;
   case &#39;drop&#39;:
    this.topText = this.topDropText;
    break;
   case &#39;loading&#39;:
    this.topText = this.topLoadingText;
    break;
  }
 },

 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;
  }
 }
}

上面是元件透過watch監聽的兩個變量,後面我們可以看到他們的改變是在touchmove事件中處理改變的。它的作用是透過它的變化來改變top slot和bottom slot的文字內容;


同時發出status-change事件給外部使用,因為可能外部自訂top slot 和bottom slot的內容,透過此事件來通知外部當前狀態以便外部進行處理。

核心函數的解析


這裡就不將所有的method列出,下面就根據處理的所以來解析對應的method函數。


首先,入口是在元件mounted生命週期的鉤子回呼中執行init函數

mounted() {
 this.init();// 当前 vue component挂载完成之后, 执行init()函数
}

init函數:

#

init() {
  this.topStatus = &#39;pull&#39;;
  this.bottomStatus = &#39;pull&#39;;
  this.topText = this.topPullText;
  this.scrollEventTarget = this.getScrollEventTarget(this.$el); // 获取滚动的dom节点
  if (typeof this.bottomMethod === &#39;function&#39;) {
   this.fillContainer(); // 判断当前滚动内容是否填满,没有执行外部传入的loadmore回调函数加载数据
   this.bindTouchEvents(); // 为当前组件dom注册touch事件
  }
  if (typeof this.topMethod === &#39;function&#39;) {
   this.bindTouchEvents();
  }
 },

 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) { // 如果没有填满内容, 执行loadmore的操作
     this.bottomStatus = &#39;loading&#39;;
     this.bottomMethod();// 调用外部的loadmore函数,加载更多数据
    }
   });
  }
 }

init函數主要是初始化狀態和事件的一些操作,下面著重分析touch事件的回呼函數的處理。


首先touchstart事件回呼處理函數

 handleTouchStart(event) {
  this.startY = event.touches[0].clientY; // 手指按下的位置, 用于下面move事件计算手指移动的距离
  this.startScrollTop = this.getScrollTop(this.scrollEventTarget); // 起始scroll dom的 scrollTop(滚动的距离)
  //下面重置状态变量
  this.bottomReached = false;
  if (this.topStatus !== &#39;loading&#39;) {
   this.topStatus = &#39;pull&#39;;
   this.topDropped = false;
  }
  if (this.bottomStatus !== &#39;loading&#39;) {
   this.bottomStatus = &#39;pull&#39;;
   this.bottomDropped = false;
  }
 }

主要是記錄初始位置和重設狀態變數。


下面繼續touchmove的回呼處理函數

 handleTouchMove(event) {
  //确保当前touch节点的y的位置,在当前loadmore组件的内部
  if (this.startY < this.$el.getBoundingClientRect().top && this.startY > this.$el.getBoundingClientRect().bottom) {
   return;
  }
  this.currentY = event.touches[0].clientY;
  let distance = (this.currentY - this.startY) / this.distanceIndex;
  this.direction = distance > 0 ? &#39;down&#39; : &#39;up&#39;;
  // 下拉刷新,条件(1.外部传入了刷新的回调函数 2.滑动方向是向下的 3.当前滚动节点的scrollTop为0 4.当前topStatus不是loading)
  if (typeof this.topMethod === &#39;function&#39; && this.direction === &#39;down&#39; &&
   this.getScrollTop(this.scrollEventTarget) === 0 && this.topStatus !== &#39;loading&#39;) {
   event.preventDefault();
   event.stopPropagation();
   //计算translate(将要平移的距离), 如果当前移动的距离大于设置的最大距离,那么此次这次移动就不起作用了
   if (this.maxDistance > 0) {
    this.translate = distance <= this.maxDistance ? distance - this.startScrollTop : this.translate;
   } else {
    this.translate = distance - this.startScrollTop;
   }
   if (this.translate < 0) {
    this.translate = 0;
   }
   this.topStatus = this.translate >= this.topDistance ? &#39;drop&#39; : &#39;pull&#39;;// drop: 到达指定的阈值,可以执行刷新操作了
  }

  // 上拉操作, 判断当前scroll dom是否滚动到了底部
  if (this.direction === &#39;up&#39;) {
   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) {
   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;;
  }
  this.$emit(&#39;translate-change&#39;, this.translate);
 }

上面的程式碼邏輯挺簡單,註解就相對不多。


重點談談checkBottomReached()函數,用來判斷目前scroll dom是否滾動到了底部。

 checkBottomReached() {
  if (this.scrollEventTarget === window) {
   return document.body.scrollTop + document.documentElement.clientHeight >= document.body.scrollHeight;
  } else {
   return this.$el.getBoundingClientRect().bottom <= this.scrollEventTarget.getBoundingClientRect().bottom + 1;
  }
 }

經過我的測試,上面的程式碼是有問題:


當scrollEventTarget是window的條件下,上面的判斷是不對的。因為document.body.scrollTop總是比正常值小1,所以用於無法滿足到達底部的條件;


當scrollEventTarget不是window的條件下,上面的判斷條件也不需要在this .scrollEventTarget.getBoundingClientRect().bottom後面加1,但加1也不會有太大視覺上的影響。


最後來看下moveend事件回呼的處理函數

 handleTouchEnd() {
  if (this.direction === &#39;down&#39; && this.getScrollTop(this.scrollEventTarget) === 0 && this.translate > 0) {
   this.topDropped = true; // 为当前组件添加 is-dropped class(也就是添加动画处理)
   if (this.topStatus === &#39;drop&#39;) { // 到达了loading的状态
    this.translate = &#39;50&#39;; // top slot的高度
    this.topStatus = &#39;loading&#39;;
    this.topMethod(); // 执行回调函数
   } else { // 没有到达,回调原点
    this.translate = &#39;0&#39;;
    this.topStatus = &#39;pull&#39;;
   }
  }
  // 处理逻辑同上
  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.$emit(&#39;translate-change&#39;, this.translate);
  this.direction = &#39;&#39;;
 }
}

總結

    下拉刷新和上拉加載更多的實現原理可以藉鑑
  1. getScrollEventTarget()獲取滾動對象,getScrollTop()獲取滾動距離,checkBottomReached()判斷是否滾動到底部;這三種方式可以藉鏡
  2. 缺點: 寫死了top slot 和bottom slot的高度,太不靈活;這個地方可以優化


##################### ###相關推薦:############vue基於mint-ui的城市選擇3級聯動實現方法############vue mint-ui 仿淘寶京收貨地址四級聯動######

詳解Vue.js 的行動裝置元件庫mint-ui實作無限捲動載入更多

#

以上是vue mint-ui中loadmore元件解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn