vue3+directive自定义指令(实现防止用户连续点击按钮)

应用场景:

directive为自定义指令,在除了v-model、v-if 等核心功能默认内置指令外,我们有时候也需要对dom元素进行底层操作,此时我们就需要用到自定义指令。

举例:

在对表单form进行提交操作时,为了防止用户连续点击造成多次调用接口而导致数据重复,可以通过directive指令自定义一个节流操作

src/directive/index.ts

export default {
  stopReClick:{
    mounted(el:any,binding:any){
      el.addEventListener('click',()=>{
        if(!el.disabled){
          el.disabled=true
          setTimeout(()=>{
            el.disabled=false
          },binding.value||1000)
        }
      })
    }
  }
}

main.ts

...
import dir from './directive/index'
...
app.directive('stopreclick', dir.stopReClick);

界面中使用(300为定义的节流的时间,若不写,则为默认的1000ms)

<button v-stopreclick="300">stopreclick</button>
posted @ 2022-07-27 22:27  南无、  阅读(1402)  评论(0)    收藏  举报