Anti-shake implementation method in Vue3
P粉055726146
2023-08-24 12:07:02
<p>I have a filter input box and want to filter a list of items. The list is large, so I want to use antishake to delay applying the filter until the user stops typing to improve user experience. This is my input box which is bound to filterText for filtering the list. </p>
<pre class="brush:php;toolbar:false;"><input type="text" v-model="state.filterText" /></pre>
Hi, first time answering a question here, so please feel free to correct my answer, I'll be very grateful. I think the most beautiful and lightweight solution is to create a directive globally that you can use randomly in all your forms.
First create a file with directives, eg. debouncer.js
Then create the anti-shake function
After defining this file, you can go to your main.js to import it and use the exported functions.
Done, when you want to use a directive in an input box, just do it like this, no need to import or anything else.
The v-model.lazy directive is very important if you choose to do it this way, because by default it will update bound properties on input events, but setting this directive will make it wait for change events, And this is the event that we emit in the antishake function. Doing so will stop v-model from automatically updating until you stop input or the timeout expires (can be set in the directive's value). Hope that makes it clear.
I didn't find a satisfactory solution because I wanted to see my bindings in the template, so I decided to share my solution. I wrote a simple debounce function and bound the behavior using the following syntax:
The template syntax is as follows: