Implement button anti-shake processing on the vue-pc side - custom instructions

foreword

  • We often deal with anti-shake and throttling of buttons and input boxes on the mobile side, but rarely do such operations on the PC side

  • However, it is also possible to carry out the anti-shake operation of the button on the PC side, which is also more reasonable. You can use it but you can’t.

  • As long as we cooperate with the vue project custom command and add global registration, we can realize the anti-shake operation of the button.

  • And this method is doing addition. After registering the custom command globally, you only need to replace @click with v-antishake (custom command)

Project custom designation - global registration package structure

 

Code implementation - project has custom directives

1. Create the antishake.js file under src/directive/module - the code is as follows

export default {
  inserted (el, binding, vnode) {
    let timer = {}
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 2000)
    })
  }
}

2. Register under src/directive/index.js

// 按钮防抖处理
import antishake from './module/antishake'
​
const install = function (Vue) {
 
  // 按钮防抖处理
  Vue.directive('antishake', antishake)
}
​
​
export default install
 
 

3. Directly use custom instructions instead of @click where button anti-shake is required on the page

// 原来点击事件
@click='事件'
// 现在点击事件-防抖处理-自定义点击事件
 v-antishake="事件"

Summarize:

After this process, I believe you also have a preliminary deep impression on the implementation of button anti-shake processing on the vue-pc side - custom instructions, but the situation we encounter in actual development is definitely different, so we have to understand Its principle remains unchanged. Come on, hit the workers!

Please point out any deficiencies, thank you -- Fengguowuhen

Guess you like

Origin blog.csdn.net/weixin_53579656/article/details/132220723