


An article explains in detail how vue2 implements the pull-down loading function with damping
Feb 20, 2023 pm 12:07 PMThis article brings you relevant knowledge about vue2. It mainly talks about how the function of damped pull-down loading is implemented in vue2. Interested friends, let’s take a look. I hope everyone has to help.
In vue, you need to bind the triggered event
<div id="testchatBox" class="chatWrap" :style="{paddingTop: chatScroollTop + 'px'}" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"> </div>
The code snippet uses three callback functions:
-
touchstart: The moment when the finger touches the screen
touchmove: The moment when the finger moves on the screen
touchend: The finger When leaving the screen
As you can see from paddingTop, we achieve the drop-down effect by controlling the padding at the top of the container distance. So our re-adjustment is to determine the value of chatScrollTop through the three callback functions above.
You can know from the name chatScrollTop that our pull-down refresh is used in the chat box container.
We need to use these variables:
data() { return { chatScroollTop: 0, // 容器距離頂部的距離 isMove: false, // 是否處于touchmove狀態(tài) startY: 0, // 當前手指在屏幕中的y軸值 pageScrollTop: 0, // 滾動條當前的縱坐標 } }
The three callback functions correspond Three stages, and our core code is also divided into three parts:
The first part: initialize the distance from the top of the current container, and initialize whether it is currently in a sliding state, and obtain the ordinate of the current scroll bar .
touchStart(e) { // e代表該事件對象,e.targetTouches[0].pageY可以拿到手指按下的 y軸點 this.startY = e.targetTouches[0].pageY // 開啟下拉刷新狀態(tài) this.isMove = false this.pageScrollTop = document.documentElement && document.documentElement.scrollTop }
Part 2: Determine the distance between the container and the top based on the ordinate difference between the current finger's current distance and the moment it touches the screen. But since it can't slide all the time, it gives a 0 -> 80 atmosphere. In order to make sliding more interesting, a step value is added to adjust the sliding distance ratio. The so-called distance ratio means that the farther the finger is from the beginning, the shorter the distance the capacity will follow to slide. Achieve a damping-like effect.
touchMove(e) { // 這個 touchMove,只要頁面在動都會發(fā)生的,所以 touching就起作用了 // 獲取移動的距離 let diff = e.targetTouches[0].pageY - this.startY let step = 60 if (diff > 0 && diff < 80 && this.pageScrollTop === 0) { step++ // 越來越大 this.chatScroollTop += (diff / (step * 0.1)) // 越向下給人的阻力感越大 this.isMove = true } }
Part 3: After releasing your finger, give a distance from the top to add a loading scroll bar.
touchEnd() { if(this.isMove) { this.chatScroollTop = 40 this.downCallback() // api拉取數(shù)據(jù) } } async downCallback() { try { // 拿數(shù)據(jù) } catch() {} finall{ this.chatScrollTop = 0 } }
Recommended learning: "vue.js video tutorial"
The above is the detailed content of An article explains in detail how vue2 implements the pull-down loading function with damping. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

The key to optimizing Vue application performance is to start from four aspects: initial loading, responsive control, rendering efficiency and dependency management. 1. Use routes and components to lazy load, reduce the initial package volume through dynamic import; 2. Avoid unnecessary responsive data, and store static content with Object.freeze() or non-responsive variables; 3. Use v-once instructions, compute attribute cache and keep-alive components to reduce the overhead of repeated rendering; 4. Monitor the package volume, streamline third-party dependencies and split code blocks to improve loading speed. Together, these methods ensure smooth and scalable applications.

End-to-end testing is used to verify whether the overall process of Vue application is working properly, involving real user behavior simulations. It covers interaction with applications such as clicking buttons, filling in forms; checking whether the data obtained by the API is displayed correctly; ensuring that operations trigger correct changes across components; common tools include Cypress, Playwright, and Selenium; when writing tests, you should use the data-cy attribute to select elements, avoid relying on easily volatile content, and reasonably mockAPI calls; it should be run after the unit test is passed, and integrated into the CI/CD pipeline, while paying attention to dealing with the instability caused by asynchronous operations.

The computed properties of Vue.js cannot directly accept parameters, which is determined by its design characteristics, but can be implemented indirectly through the computed properties of methods or return functions. 1. Methods: Parameters can be passed and used in templates or listeners, such as formatName('John','Doe'); 2. Encapsulate the computed attributes into the form of a return function: such as formatName returns a function that accepts parameters, and call formatName()('Jane','Smith') in the template. The method of use is usually recommended because it is clearer and easier to maintain, and the way of returning functions is suitable for special scenarios where internal state and external values ??are required.

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

To handle API errors in Vue, you must first distinguish the error types and handle them uniformly to improve the user experience. The specific methods are as follows: 1. Distinguish the error types, such as network disconnection, non-2xx status code, request timeout, business logic error, etc., and make different responses through judgment error.response in the request; 2. Use the axios interceptor to realize a unified error handling mechanism, and perform corresponding operations according to the status code in the response interceptor, such as 401 jumps to login page, 404 prompts the resource does not exist, etc.; 3. Pay attention to user experience, feedback errors through Toast prompts, error banners, retry buttons, etc., and close the loading status in a timely manner. These methods can effectively improve the robustness and user-friendliness of the application.

TheVuecreatedlifecyclehookisusedforearlycomponentinitializationtasksthatdonotrequireDOMaccess.Itrunsafterdatapropertiesaremadereactive,computedpropertiesaresetup,methodsarebound,andwatchersareactive,butbeforethetemplateisrenderedorDOMelementsarecreat

nextTick is used in Vue to wait for the DOM to be updated before performing operations that depend on the DOM state. When data changes, Vue asynchronously batch updates the DOM to improve performance, so directly accessing or operating the DOM may not be able to get the latest status; using nextTick ensures that the code runs after the DOM is updated. Common scenarios include: 1. Accessing the updated DOM element size; 2. Focusing on the input box after rendering; 3. Triggering third-party libraries that rely on DOM; 4. Reading layout attributes such as offsetHeight. Use this.$nextTick() or awaitthis.$nextTick() to avoid errors and need to move the DOM operation into the nextTick callback.

Server-siderendering(SSR)inVueimprovesperformanceandSEObygeneratingHTMLontheserver.1.TheserverrunsVueappcodeandgeneratesHTMLbasedonthecurrentroute.2.ThatHTMLissenttothebrowserimmediately.3.Vuehydratesthepage,attachingeventlistenerstomakeitinteractive
