An in-depth analysis of the ultimate anti-shake/throttling in Vue3
This article brings you the ultimate anti-shake/throttle in Vue 3 (including common methods of anti-shake/throttle). This article will not only describe the original anti-shake or throttling methods. , will also bring a new packaging method, which is simpler and clearer to use.
In the front-end development process, the process involving interaction with the user basically needs to be processed. The normal operation is to add anti-shake at the corresponding position. Or throttling.
Add anti-shake or throttling functions: first, to prevent users from frequent operations; second, to save certain server resources and reduce resource waste.
Anti-shake or throttling principle
Anti-shake (debounce)
If the user operates multiple times frequently, the last time will prevail. Of course, the first time can also be used as the basis for data updates or network resource requests to eliminate redundant operations or reduce a certain amount of waste of request resources. [Related recommendations: vuejs video tutorial, web front-end development】
Sample code
function debounce (fn, delay = 300){ let timer = null return function (...args) { clearTimeout(timer) timer = setTimeout(()=>{ fn.call(this, ...args) }, delay); } }
Use
debounce(()=> count += 1, 1000)
Throttle (throttle)
Within a certain time range, if the user triggers multiple times, it will only be executed once to prevent the user from Purpose of frequent operations.
Sample Code
let timer = null function throttle (fn, delay = 300) { if(timer == null){ timer = setTimeout(() => { fn() clearTimeout(timer) timer = null }, delay); } }
Usage
throttle(()=> count += 1, 1000)
Environment Description
vue 3
- vite
New package
Here I divide it into two Let’s talk about each module. One is anti-shake; the other is throttling.
Although the difference between the two is not very big, there is still a difference. Get in the car, guys.
Debounce
Let’s first look at the common package contents.
Common encapsulation-1
Code
function debounce (fn, delay = 300){ let timer = null return function (...args) { if(timer != null){ clearTimeout(timer) timer = null } timer = setTimeout(()=>{ fn.call(this, ...args) }, delay); } }
Usage
const addCount = debounce(()=> count.value += 1, 1000)
Common encapsulation-2
Code
let timer = null function debounce (fn, delay = 1000){ if(timer != null){ clearTimeout(timer) timer = null } timer = setTimeout(fn, delay) }
Use
const addCount = () => debounce(()=> count.value += 1, 1000)
New package
Here we need to use the ## in vue 3
#customRef to implement our new approach. I won’t write in detail here. I add comments directly above each line of code. I believe my friend you can understand.
// 从 vue 中引入 customRef 和 ref import { customRef, ref } from "vue" // data 为创建时的数据 // delay 为防抖时间 function debounceRef (data, delay = 300){ // 创建定时器 let timer = null; // 对 delay 进行判断,如果传递的是 null 则不需要使用 防抖方案,直接返回使用 ref 创建的。 return delay == null ? // 返回 ref 创建的 ref(data) : // customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。 customRef((track, trigger) => { return { get () { // 收集依赖 track() // 返回当前数据的值 return data }, set (value) { // 清除定时器 if(timer != null){ clearTimeout(timer) timer = null } // 创建定时器 timer = setTimeout(() => { // 修改数据 data = value; // 派发更新 trigger() }, delay) } } }) }
// 创建 const count = debounceRef(0, 300) // 函数中使用 const addCount = () => { count.value += 1 } // v-model 中使用 <input type="text" v-model="count">
throttle
We are still the same, first See common package contents.Common encapsulation-1
Codelet timer = null function throttle (fn, delay = 300) { if(timer == null){ timer = setTimeout(() => { fn() clearTimeout(timer) timer = null }, delay); } }
const addCount = () => throttle(()=> count.value += 1, 1000)
Common encapsulation-2
Codefunction throttle (fn, delay = 300) { let timer = null return function (...args) { if(timer == null){ timer = setTimeout(() => { fn.call(this, ...args) clearTimeout(timer) timer = null }, delay); } } }
const addCount = throttle(()=> count.value += 1, 1000)
New package
Throttling and anti-shake are similar in packaging and use. Code// data 为创建时的数据 // delay 为节流时间 function throttleRef (data, delay = 300){ // 创建定时器 let timer = null; // 对 delay 进行判断,如果传递的是 null 则不需要使用 节流方案,直接返回使用 ref 创建的。 return delay == null ? // 返回 ref 创建的 ref(data) : // customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。 customRef((track, trigger) => { return { get () { // 收集依赖 track() // 返回当前数据的值 return data }, set (value) { // 判断 if(timer == null){ // 创建定时器 timer = setTimeout(() => { // 修改数据 data = value; // 派发更新 trigger() // 清除定时器 clearTimeout(timer) timer = null }, delay) } } } }) }
// 创建 const count = debounceRef(0, 300) // 函数中使用 const addCount = () => { count.value += 1 } // v-model 中使用 <input type="text" v-model="count">
Summary
The above is the ultimate defense in
Vue 3 Shake/throttling (including common methods of anti-shaking/throttling) The entire content of this article. If there are any shortcomings or if you have a better way or other unique insights, please feel free to comment and send a private message.
vue 2 can click here?
Implementing CustomRef method anti-shake/throttling in Vue 2
vuejs introductory tutorial, Basic programming video)
The above is the detailed content of An in-depth analysis of the ultimate anti-shake/throttling in Vue3. 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

AI Hentai Generator
Generate AI Hentai for free.

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

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

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

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

What is front-end ESM? Specific code examples are required. In front-end development, ESM refers to ECMAScriptModules, a modular development method based on the ECMAScript specification. ESM brings many benefits, such as better code organization, isolation between modules, and reusability. This article will introduce the basic concepts and usage of ESM and provide some specific code examples. The basic concept of ESM In ESM, we can divide the code into multiple modules, and each module exposes some interfaces for other modules to

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning
