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<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 '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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.