


vue.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<-height-distance){ //console.log("上拉"); //do something }
In order to prevent multiple triggers, you need to add 2 switches;
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 ref="wrapper" class="list-wrapper"> <p class="scroll-content"> <slot></slot> </p> </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 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='{path:"/film-detail/"+v.id}'> <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>
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 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='PullingUpWord'></Loading> </p> </p> <transition name="pullDown"> <Loading class="pullDown" v-show="inPullDown" :loadingWord='PullingDownWord'></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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
