Vue writes (preventReClick) anti riot point + de bounce and throttle functions

Keywords: Javascript html5 Vue.js

Several have been tried before and have no effect. Reasons:

1. The writing method of vue is a little different from that of ordinary, because this of vue is not only the current component object, but also inherits the vue object upward (the difference can be seen below)
2. Call and apply can only inherit the parent, not deep inheritance
3. Because deep inheritance requires recursive or multi-layer nested functions, the amount of code is large and difficult to maintain, so the following method is recommended

1. preventReClick

Problem: when clicking a button quickly, the interface will be called repeatedly. In order to prevent this situation, it is best to use function anti shake or function interception to deal with the corresponding button. However, there are too many buttons to be modified, so change another method and use instructions to achieve the effect of acquaintance.

1. Create utils folder and create preventReClick.js file under this folder

import Vue from 'vue'
// Mount a pointer preventReClick on vue
const preventReClick = Vue.directive('preventReClick', {
    inserted: function (el, binding) {
        console.log(el.disabled)
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 3000)
                //binding.value can be set by yourself. If set, follow the set time
                //For example: v-preventReClick='500 '
            }
        })
    }
});
export { preventReClick }

2. Global reference in main.js

import './utils/preventReClick.js'

3. Directly use the v-preventReClick instruction in the button component

 <a-button type="primary" @click="handleSubmit" v-preventReClick >preservation</a-button>

1. debounce

meaning:
The user stops the operation and executes the function; As long as the operation is not stopped, the operation in the function will never be executed

Usage scenario: anti shake is often applied to search input by users to save request resources,
For example, if the input value of the original watch user changes, immediately request the interface, add anti shake, and stop the input operation before accessing the interface
code:

/**
 * @description After the function anti shake triggers the high-frequency time, the function will only be executed once in n seconds. If the high-frequency time triggers again in n seconds, the time will be recalculated.
 * @param {Function} func Functions to execute
 * @param {Number} wait The interval is 200ms by default
 * @param {Boolean} immediate  Whether to execute immediately. The true (default) table executes immediately. The false table does not execute immediately
 * @return {*}
 * @author liuxin
 */
export function VueDebounce(func, wait = 200, immediate = true) {
    let timeout = null;  // timer
    return function () {
        let that = this, // this object
            args = arguments; // parameter
        if (timeout) clearTimeout(timeout);
        if (immediate === true) { // Execute now
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) {
                // func.apply(that, args); //  Common usage
                that[func](...args); // vue usage
            }
        }
        else { // Non immediate execution
            timeout = setTimeout(() => {
                // func.apply(this, args); //  Common usage
                that[func](...args); // vue usage
            }, wait);
        }
    }
}

Usage:

methods: {
    /**
     * Click event function anti shake
     * Usage: < El button @ Click = "debouncehandel" > Click to test < / El button >
     */
    debounceHandel: VueDebounce("handlerFunc"),
 
    /**
     * Click event: function actually executed
     */
    handlerFunc(type) {
      console.log("Test anti shake events");
      this.$emit("click","This is a parameter"); // If you use normal usage, $emit will not be found here, because this also inherits the object of vue
    },
  }
 

2. throttle

Meaning: high frequency time trigger, but it will only be executed once in n seconds, so throttling will dilute the execution frequency of the function.. It is a fixed process. If it is limited to 1s, it will be executed only once within 1s. In any case, the corresponding operation will be executed within 1s
Usage scenario: similar to the anti shake usage scenario, the key is that feedback is required within a fixed time (1s), and throttling is required for feedback, that is, function operations will be executed at a fixed time whether the user stops the operation or not
Code: the usage is consistent with the function anti shake
/**

 * @description Function throttling
 * @param {Function} func function
 * @param {Number} wait Milliseconds of delayed execution,Default 200
 * @param {Number} type 1 Table timestamp version, 2 table timer version
 */
function VueThrottle(func, wait=200 ,type) {
    if(type===1){
        let previous = 0;
    }else if(type===2){
        let timeout;
    }
    return function() {
        let that= this;
        let args = arguments;
        if(type===1){
            let now = Date.now();
 
            if (now - previous > wait) {
                // func.apply(that, args); //  Common usage
                that[func](...args); // vue usage
                previous = now;
            }
        }else if(type===2){
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    // func.apply(that, args)
                    that[func](...args); // vue usage
                }, wait)
            }
        }
    }
}

Partial original

Posted by xtian on Tue, 21 Sep 2021 18:06:41 -0700