Home > Web Front-end > JS Tutorial > body text

vue.js mobile terminal implements pull-up loading and pull-down refresh

php中世界最好的语言
Release: 2018-04-18 10:54:25
Original
4400 people have browsed it

This time I will bring you the vue.js mobile terminal to implement pull-up, load, and pull-down refresh. The vue.js mobile terminal implements pull-up, load, and pull-down refresh. What are the precautions? . Here are the actual cases. One Get up and take a look.

Just like horizontal scrolling, we still use the better-scroll library to implement it. Since better has been updated to a new version, it was previously version 0.7. After updating, I found that it is now version 1.2.6, and there are more new versions. It’s a relatively easy-to-use API, so I also rewrote the previous code and used the new API to implement pull-up loading and pull-down refresh.

First write the basic style, which is skipped here, and then introduce the better-scroll library

import BScroll from 'better-scroll'
Copy after login

Secondly, when instantiating scroll in mountedLifecycle, you can get the data and then new, or you can new first and then call refresh after getting the data.

You need to pass in a configuration parameter during the instance. Since there are many parameters, please refer to the documentation for details. Here are only two key points:

//是否开启下拉刷新,可传入true或者false,如果需要更多配置可以传入一个对象
pullDownRefresh:{
  threshold:80,
  stop:40
}
//是否开启上拉加载,同上,上拉无stop参数,这里需要注意是负数
pullUpLoad:{
  threshold:-80,
}
/**
 * 
 * @param threshold 触发事件的阀值,即滑动多少距离触发
 * @param stop 下拉刷新后回滚距离顶部的距离(为了给loading留出一点空间)
 */
Copy after login

The above numbers personally feel more appropriate, but there is a problem here. Since I use Taobao flexible.js for adaptation, this leads to: the distance of 80 is appropriate under Android, but under iPhone 6s, due to being scaled 3, so now 80 is about 27 on iPhone 6s.

Therefore, for screens with different zoom levels, the corresponding zoom ratios need to be multiplied.

Taobao flexible.js actually already has this method of obtaining the screen zoom ratio. Here you can get it directly from it:

//在util.js里面加一个方法
export function getDeviceRatio(){
  var isAndroid = window.navigator.appVersion.match(/android/gi);
  var isIPhone = window.navigator.appVersion.match(/iphone/gi);
  var devicePixelRatio = window.devicePixelRatio;
  var dpr;
  if (isIPhone) {
    // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
    if (devicePixelRatio >= 3) {        
      dpr = 3;
    } else if (devicePixelRatio >= 2){
      dpr = 2;
    } else {
      dpr = 1;
    }
  } else {
    // 其他设备下,仍旧使用1倍的方案
    dpr = 1;
  }
  return dpr
}
Copy after login
import{ DEVICE_RATIO} from '../base/js/api.js'
/*获取当前缩放比*/
const DEVICE_RATIO=getDeviceRatio();
 /*下拉配置*/
const DOWN_CONFIG={
 threshold:80*DEVICE_RATIO,
 stop:40*DEVICE_RATIO
}
/*上拉配置*/
const UP_CONFIG={
 threshold:-80*DEVICE_RATIO,
}
this.scroller = new BScroll(scrollWrap,{
 click:true,
 probeType:3,
 pullDownRefresh:DOWN_CONFIG,
 pullUpLoad:UP_CONFIG
});
Copy after login

After instantiation, the next step is to listen for pull-up and pull-down events. betterScroll has added some new events, the main ones are:

/*下拉事件*/
this.scroller.on('pullingDown',()=> {});
/*上拉事件*/
this.scroller.on('pullingUp',()=>{});
Copy after login

After triggering the pull-up or pull-down event, we need to call this.scroller.finishPullDown() or this.scroller.finishPullUp() to notify the better-scroll event is completed.

The general process is as follows:

this.scroller.on('pullingDown',()=> {
  
  <!-- 1. 发送请求获取数据 -->
  
  <!-- 2. 获取成功后,通知事件完成 -->
  
  <!-- 3. 修改data数据,在nextTick调用refresh -->
});
Copy after login

Usually after the operation is completed, we need to manually trigger the refresh method to recalculate the scrollable distance, so we can write a watch to monitor changes in the data, so that we only need to change the data and do not need to call the refresh method every time after operating the data.

watch:{
 dataList(){
  this.$nextTick(()=>{
   this.scroller.refresh(); 
  }) 
 }
},
Copy after login

If the version you are using is still old, you can make a judgment during the on(scroll) event to implement the function

this.scroller.on("scroll",(pos)=>{ 
  //获取整个滚动列表的高度
  var height=getStyle(scroller,"height");
  //获取滚动外层wrap的高度
  var pageHeight=getStyle(scrollWrap,"height");
  //触发事件需要的阀值
  var distance=80*DEVICE_RATIO;
  //参数pos为当前位置
  if(pos.y>distance){ 
    //console.log("下拉");
    //do something
   
  }else if(pos.y-pageHeight<-height-distance){
    //console.log("上拉");
    //do something
  }
Copy after login

In order to prevent multiple triggers, you need to add 2 switches;

var onPullUp=true;
var onPullDown=true;
Copy after login

Each time an event is triggered, set the corresponding switch to false, and then reset it to true after the operation is completed. Otherwise, multiple pull-downs or pull-ups will trigger multiple events. By setting the switch, you can ensure that only one event is running at a time.

Finally, package it into a component

 <template>
  <p ref="wrapper" class="list-wrapper"> 
    <p class="scroll-content">    
      <slot></slot>     
    </p>   
  </p>
</template>
Copy after login

Since the specific content that needs to be scrolled is different for each page, a slot is used to distribute it.

The parameters required by the component are passed in from the parent, received through prop and set the default value

 export default {
  props: {
   dataList:{
    type: Array,
    default: []
   },
   probeType: {
    type: Number,
    default: 3
   },
   click: {
    type: Boolean,
    default: true
   },  
   pullDownRefresh: {
    type: null,
    default: false
   },
   pullUpLoad: {
    type: null,
    default: false
   },  
  }
Copy after login

After the component is mounted, it does not process the event directly when the event is triggered, but sends an event to the parent. The parent receives the event through the template v-on and processes the subsequent logic

mounted() {
  this.scroll = new BScroll(this.$refs.wrapper, {
      probeType: this.probeType,
      click: this.click,    
      pullDownRefresh: this.pullDownRefresh,
      pullUpLoad: this.pullUpLoad,
    })
  this.scroll.on('pullingUp',()=> {
    if(this.continuePullUp){
      this.beforePullUp();
      this.$emit("onPullUp","当前状态:上拉加载");
    }
  });
  this.scroll.on('pullingDown',()=> {
    this.beforePullDown();
    this.$emit("onPullDown","当前状态:下拉加载更多");
  }); 
}
Copy after login

When using the parent component, you need to pass in the configuration parameter Props and process the events emitted by the child component, and replace the slot tag with specific content

  <Scroller 
    id="scroll"
    ref="scroll" 
    :dataList="filmList"
    :pullDownRefresh="DOWN_CONFIG"
    :pullUpLoad="UP_CONFIG"
    @onPullUp="pullUpHandle"
    @onPullDown="pullDownHandle"
   >
    <ul>
       <router-link class="film-list" v-for="(v,i) in filmList" :key="v.id" tag="li" :to=&#39;{path:"/film-detail/"+v.id}&#39;>
          <p class="film-listimg">
             <img v-lazy="v.images.small" alt="" />        
          </p>
          <p class="film-listdetail">
            <p class="film-listdetailtitle">{{v.title}}</p>
            <p class="film-listdetaildirector">导演:{{filterDirectors(v.directors)}}</p>
            <p class="film-listdetailyear">年份:{{v.year}}<span>{{v.stock}}</span></p>
            <p class="film-listdetailtype">类别:{{v.genres.join(" / ")}}<span></span></p>
            <p class="film-listdetailrank">评分:<span>{{v.rating.average}}分</span></p>
          </p>             
        </router-link>
     </ul>     
   </Scroller>
Copy after login

The parent component can obtain the child component through this.$refs.xxx, and can call the method in the child component;

 computed:{
    scrollElement(){
      return this.$refs.scroll
    }
  }
Copy after login

The complete scroller component content is as follows

   <template>
     <p ref="wrapper" class="list-wrapper"> 
       <p class="scroll-content">    
         <slot></slot>
         <p>
           <PullingWord v-show="!inPullUp&&dataList.length>0" :loadingWord="beforePullUpWord"></PullingWord>
           <Loading v-show="inPullUp" :loadingWord=&#39;PullingUpWord&#39;></Loading>
         </p>    
       </p> 
       <transition name="pullDown">
         <Loading class="pullDown" v-show="inPullDown" :loadingWord=&#39;PullingDownWord&#39;></Loading>
       </transition> 
     </p>
   </template>
   <script >
    import BScroll from 'better-scroll'
    import Loading from './loading.vue'
    import PullingWord from './pulling-word'
    const PullingUpWord="正在拼命加载中...";
    const beforePullUpWord="上拉加载更多";
    const finishPullUpWord="加载完成";
    const PullingDownWord="加载中...";
    export default {
     props: {
      dataList:{
       type: Array,
       default: []
      },
      probeType: {
       type: Number,
       default: 3
      },
      click: {
       type: Boolean,
       default: true
      },  
      pullDownRefresh: {
       type: null,
       default: false
      },
      pullUpLoad: {
       type: null,
       default: false
      },  
     },
     data() {
       return { 
         scroll:null,
         inPullUp:false,
         inPullDown:false,
         beforePullUpWord,
         PullingUpWord,
         PullingDownWord,
         continuePullUp:true
       }
     },
      
     mounted() {
       setTimeout(()=>{
         this.initScroll();
         this.scroll.on('pullingUp',()=> {
           if(this.continuePullUp){
             this.beforePullUp();
             this.$emit("onPullUp","当前状态:上拉加载");
           }
         });
         this.scroll.on('pullingDown',()=> {
           this.beforePullDown();
           this.$emit("onPullDown","当前状态:下拉加载更多");
         });
       },20)
       
     },
     methods: {
       initScroll() {
         if (!this.$refs.wrapper) {
           return
         }
         this.scroll = new BScroll(this.$refs.wrapper, {
           probeType: this.probeType,
           click: this.click,    
           pullDownRefresh: this.pullDownRefresh,
           pullUpLoad: this.pullUpLoad,
         })
       },
       beforePullUp(){
         this.PullingUpWord=PullingUpWord;
         this.inPullUp=true;
       }, 
       beforePullDown(){
         this.disable();
         this.inPullDown=true;
       },
       finish(type){
         this["finish"+type]();
         this.enable();
         this["in"+type]=false; 
       },
       disable() {
         this.scroll && this.scroll.disable()
       },
       enable() {
         this.scroll && this.scroll.enable()
       },
       refresh() {
         this.scroll && this.scroll.refresh()
       }, 
       finishPullDown(){
         this.scroll&&this.scroll.finishPullDown()
       },
       finishPullUp(){
         this.scroll&&this.scroll.finishPullUp()
       },   
     },
        
     watch: {
       dataList() {        
         this.$nextTick(()=>{
           this.refresh();            
         }) 
       }
     },
     components: {
       Loading,
       PullingWord
     }
    }
   </script>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting content, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:



The above is the detailed content of vue.js mobile terminal implements pull-up loading and pull-down refresh. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!