vue2 global directive-limit button click events within a certain period of time

Demand: When clicking a button to send a request, if you click it quickly and continuously, it is easy to send multiple requests. How can you click the button multiple times within a certain period of time but only send one request?

Solutions:

If you click multiple times and only send one request, you can use function anti-shake throttling; of course, you can also write a local or global custom instruction to limit the click event of the button.

Solution:

What is used this time is to use global instructions to limit the click events of buttons to facilitate the use of other pages (useful for personal testing).

This article can be copied and pasted directly (but please understand the logic of the code first):

  1. First, create a new directive folder in the src directory, create a new file in this folder, name it: preventClick.js, and write the following code in the file:
// 设置全局指令,对button按钮进行点击限制
export default {
    install(Vue) {
      Vue.directive('preventClick', {
        inserted(button, bind) {
          button.addEventListener('click', () => {
            if (!button.disabled) { // 按钮有disabled属性
              button.disabled = true;
              setTimeout(() => {
                button.disabled = false
              }, 5000)
            }
          })
        }
      })
    }
}
  1. Register globally in main.js
// 全局指令
import preventClick from '@/directive/preventClick.js'
Vue.use(preventClick)
  1. Just v-preventClick directly in the file you need to use
<button v-if="score.enabledStatu" @click="stopScan(text, score)" class="options" v-preventClick>停止</button>

Summarize:

There are many needs, but there are also many solutions. Let’s analyze them slowly. If this article is not comprehensive, please let me know.

Guess you like

Origin blog.csdn.net/weixin_42234899/article/details/129037441