Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use anti-shake and throttling in Vue components

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to use anti-shake and throttling in Vue components. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

How to use anti-shake and throttling in Vue components?

Here's an example of how to use anti-shake and throttling to control observers and event handlers in Vue components.

Be careful when listening for frequently triggered events, such as user typing in the input box, window resizing, scrolling, Intersection Observer events.

These events are always triggered frequently, perhaps every few seconds. It is obviously unwise to initiate an fetch request (or similar behavior) for each event.

All we need to do is slow down the execution of the event handler. This buffer technology is anti-shake (debounce) and throttling (throttle).

In this article, you will learn how to use anti-shake and throttling control observer (watchers) and event handlers in Vue components.

1. The observer shivers.

Let's start with a simple component, and our task is to output the text that the user enters into the text box to the console:

{{value}}

Export default {data () {return {value: "",};}, watch: {value (newValue, oldValue) {console.log ("Value changed:", newValue);}

Open demo:

Https://codesandbox.io/s/vue-input-szgn1?file=/src/App.vue

Open demo and type a few characters in the input box. Each time you enter, the value is log to the console.

We print the log by using the watcher to listen for value data properties. But if you want to add a GET request that takes value as a parameter to the viewer's callback, you shouldn't expect the request to be made too often.

Let's do some anti-shaking on the behavior of printing console logs. The core idea is to create an anti-shake function and then call it within the observer.

I chose the anti-shake implementation of 'lodash.debounce' here, but you are free to choose the implementation you like.

Let's apply the anti-shake logic to the component:

{{value}}

Import debounce from "lodash.debounce"; export default {data () {return {value: ",};}, watch: {value (... args) {this.debouncedWatch (.args);},}, created () {this.debouncedWatch = debounce ((newValue, oldValue) = > {console.log ('New value:', newValue);}, 500) }, beforeUnmount () {this.debouncedWatch.cancel ();},}

Try demo.

Https://codesandbox.io/s/vue-input-debounced-4vwex?file=/src/App.vue

If you open this demo, you will find that from the user's point of view, it doesn't change much: you are still free to enter characters as you did in the previous demo.

But there is one difference: the log of the new input value is not printed to the console until after the last 500ms entered. This means that anti-shaking is in effect.

The implementation of the observer's anti-shaking requires only three simple steps:

In the create () hook, create an anti-shake callback and assign it to the instance: this.debouncedWatch = debounce (., 500).

Call this.debouncedWatch () in the observer callback watch.value () {...} with the correct parameter.

Finally, this.debouncedWatch.cancel () is called in the beforeUnmount () hook to cancel the execution of all anti-shake functions that are still in pending before uninstalling the component.

In the same way, you can apply anti-shake to observers of any data attribute. Then you can safely perform some heavy operations inside the anti-shake callback, such as network requests, heavy DOM operations, and so on.

two。 Event handler anti-shake

In the previous section, I showed how to use anti-shake for observers, so what about regular event handlers?

We reuse the previous example of user input data into the input box, but this time we add an event handler to the input box.

As usual, if you don't take any buffering measures, every time the value is modified, it will be printed to the console:

Export default {methods: {handler (event) {console.log ('New value:', event.target.value);}

Try demo:

Https://codesandbox.io/s/vue-event-handler-plls4?file=/src/App.vue

Open the demo and type a few characters in the input box. Take a look at the console: you will find that a log is printed every time you type.

Similarly, if you can perform some heavy operations (such as network requests), it is not appropriate.

To use anti-shake for event handlers, you can refer to the following:

Import debounce from "lodash.debounce"; export default {created () {this.debouncedHandler = debounce (event = > {console.log ('New value:', event.target.value);}}, beforeUnmount () {this.debouncedHandler.cancel ();}}

Try demo:

Https://codesandbox.io/s/vue-event-handler-debounced-973vn?file=/src/App.vue

Open demo and enter some characters. The component prints the log of the new input value to the console only after the last 500ms entered. Anti-shaking is working again!

The anti-shake implementation of the event handler requires only three steps:

. In the create () hook, immediately after creating the instance, assign the anti-shake callback debounce (event = > {...}, 500) to this.debouncedHandler.

Assign debouncedHandler to v-on:input in the template of the input box:

Finally, before unloading the component, call this.debouncedHandler.cancel () in the beforeUnmount () hook to cancel all function calls that are still in pending.

On the other hand, these examples apply anti-shake techniques. However, the same way can be used to create throttling functions.

3. Be careful

You may not understand: why not just create anti-shake functions in the component's method option and then call these methods as event handlers in template?

/ /... Methods: {/ / Why not? DebouncedHandler: debounce (function () {...}}, 500)} / /.

This is much easier than creating an anti-shake function on an instance object.

For example:

Import debounce from "lodash.debounce"; export default {methods: {/ / Don't do this! DebouncedHandler: debounce (function (event) {console.log ('New value:', event.target.value);}})}

Try demo.

Https://codesandbox.io/s/vue-event-handler-debounced-incorrectly-320ci?file=/src/App.vue

Instead of creating an anti-shake callback in the created () hook, the anti-shake callback is assigned to methods.debouncedHandler.

If you have tried demo, you will find that it works!

The problem is that options objects, including methods, exported by the component using export default {...} will be reused by the component instance.

If there are more than two instances of components in the web page, then all components will apply the same anti-shake function methods.debouncedHandler-this will cause anti-shake failure.

4. Summary

In Vue, anti-shake and throttling can be easily applied to observers and event handlers.

The core logic is to create an anti-shake or throttling callback in the created () hook and assign a value to the instance.

/ /... Created () {this.debouncedCallback = debounce ((... args) = > {/ / The debounced callback}, 500);}, / /.

A) then call the anti-shake function on the instance inside the observer:

/ /... Watch: {value (... args) {this.debouncedCallback (.args);},}, / /.

B) or set an event handler in template:

After that, every time you call this.debouncedCallback (. Args), even if the execution frequency is very high, the internal callback can buffer the execution.

This is how to use anti-shake and throttling in the Vue components shared by Xiaobian. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report