search
HomeWeb Front-endJS Tutorialvue.js mobile terminal implements pull-up loading and pull-down refresh

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'

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留出一点空间)
 */

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

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',()=>{});

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

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(); 
  }) 
 }
},

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<p style="text-align: left;">
In order to prevent multiple triggers, you need to add 2 switches;</p><pre class="brush:php;toolbar:false">var onPullUp=true;
var onPullDown=true;

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> 
    </p>
<p>    
      <slot></slot>     
    </p>   
  
</template>

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

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","当前状态:下拉加载更多");
  }); 
}

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>
    <ul>
       <router-link>
          <p>
             <img  alt="vue.js mobile terminal implements pull-up loading and pull-down refresh" >        
          </p>
          <p>
            </p>
<p>{{v.title}}</p>
            <p>导演:{{filterDirectors(v.directors)}}</p>
            <p>年份:{{v.year}}<span>{{v.stock}}</span></p>
            <p>类别:{{v.genres.join(" / ")}}<span></span></p>
            <p>评分:<span>{{v.rating.average}}分</span></p>
                       
        </router-link>
     </ul>     
   </scroller>

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

The complete scroller component content is as follows

   <template>
     <p> 
       </p>
<p>    
         <slot></slot>
         </p>
<p>
           <pullingword>0" :loadingWord="beforePullUpWord"></pullingword>
           <loading></loading>
         </p>    
        
       <transition>
         <loading></loading>
       </transition> 
     
   </template>
   <script>
    import BScroll from &#39;better-scroll&#39;
    import Loading from &#39;./loading.vue&#39;
    import PullingWord from &#39;./pulling-word&#39;
    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(&#39;pullingUp&#39;,()=> {
           if(this.continuePullUp){
             this.beforePullUp();
             this.$emit("onPullUp","当前状态:上拉加载");
           }
         });
         this.scroll.on(&#39;pullingDown&#39;,()=> {
           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>

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!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),