How to implement anti-shake in input in Vue

Anti-shake usage scenarios:

  • Log in or send text messages to prevent users from clicking too fast, so that too many requests are sent, and anti-shake is required
  • When adjusting the size of the browser window, the number of resizes is too frequent, resulting in too many calculations. It needs to be in place at one time, so the anti-shake is used
  • When searching in the input box, when the input box event is triggered, the input content will be refreshed every time (clear the previous timer), that is to say, as long as you keep inputting content, it will never request

The principle of anti-shake:

  • The callback is executed n seconds after the event is triggered, and if it is triggered again during these n seconds, the timer is restarted

Implementation idea:

 To achieve anti-shake:

  1. Create a utils folder in the root directory and create a utils.js file in the utils folder
  2. Add code under utils.js
    export function debounce(fn, wait) {
        let timeout = null;
        wait = wait || 600;
        return function () {
          let that = this;
          if(timeout !== null)   clearTimeout(timeout);  
          timeout = setTimeout(() => {
            fn.apply(that);
          }, wait);
        }    
    }

  3. Introduce on required pages
    //在需要的页面引入
    import {debounce} from "@/utils/utils"

  4. trigger input event
     <input v-model="value" @input="changeValue" />

  5. Call the changeValue method
    methods:{
        changeValue:debounce(function(){
         console.log(111)
        }, 1000)  //这个1000代表事件延迟1000ms执行
    }

Guess you like

Origin blog.csdn.net/weixin_55521186/article/details/130614497