Vue prevents multiple triggers of requested operations after successive clicks in a short period of time

  • 2021-09-16 06:18:53
  • OfStack

If you click the Submit button continuously, you may submit data repeatedly, resulting in errors. The solution can be to use disabled to limit clicks. The experience is not very good. All share the following methods for everyone


<el-button @click="throttle()"> Test </el-button> 
export default {
 data(){
  return {
   lastTime:0 // On by default 1 The second click time is 0 
  }
 }
}

methods:{
 throttle(){
  // Gets the timestamp of the current time 
  let now = new Date().valueOf();
  // No. 1 1 Secondary clicks 
  if(this.lastTime == 0){
   console.log(' Trigger event ');
   this.lastTime = now;
  }else{
   if((now-this.lastTime) > 2000){
    // Reset on 1 Time to click, 2000 I set it up myself 2 Second interval, which can be changed according to your own needs 
    this.lastTime = now;
    console.log(' Interval greater than 2 Seconds, triggering method ');
    // Add the method you want to call 
   }else{
    console.log(' Do not trigger ');
   }
  }
  },
}

Although this approach is good, it may not be easy to handle when the request times out (network reasons, too much data). Consider controlling by whether the backend returns res. The method needs to be improved! For reference only ~

Supplementary knowledge: To solve the problem that module in vuex needs to be introduced one by one when there are too many module

In the project development, vuex is used. If the project is too large, vuex needs modularization. However, if module scores too much, we need to introduce it one by one in index. js of store, which is too troublesome. Therefore, webpack has a configuration, which can solve this problem without introducing it many times. It is good news for lazy cancer patients.

Here's the solution


import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
 const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
 const value = modulesFiles(modulePath)
 modules[moduleName] = value.default
 return modules
}, {})
const store = new Vuex.Store({
 modules,
 getters
})
export default store

After configuring this, there is no need to introduce modules one by one;


Related articles: