vue 全局指令实现防止按钮重复点击 防抖

vue 全局指令实现防止按钮重复点击 防抖

指令代码

通过为按钮设置disabled属性在3秒内阻止重复点击,设置定时器在3秒后移除disabled属性

export const preventClick = {
  inserted(el, binding) {
    el.addEventListener('click', () => {
      if (!el.disabled) {
        el.disabled = true
        setTimeout(() => {
          el.disabled = false
        }, binding.value || 3000)
      }
    })
  }
}

附:批量定义全局指令

定义指令

1、创建components/directive/directive.js

/**
 * 苹果手机下拉框无法输入问题
 * 使用方式:在对应标签上加上v-clickoutside
 */
export const clickoutside = {
  bind: function(el) {
    const dom = el.querySelector('.el-input__inner')
    if (dom) {
      dom.addEventListener('focus', function() {
        setTimeout(() => {
          dom.removeAttribute('readonly')
        }, 200)
      })
    }
  }
}

/**
 * 防止按钮重复点击
 * 使用方式:在对应标签上加上v-preventClick
 */
export const preventClick = {
  inserted(el, binding) {
    el.addEventListener('click', () => {
      if (!el.disabled) {
        el.disabled = true
        setTimeout(() => {
          el.disabled = false
        }, binding.value || 3000)
      }
    })
  }
}

export default { clickoutside, preventClick }

2、创建components/directive/index.js

import directives from './directive'

const directiveInstalls = []
const directiveList = []

Object.keys(directives).forEach(key => {
  const install = function(Vue) {
    Vue.directive(key, directives[key])
  }
  directives[key].install = install
  directiveInstalls.push(install)
  directiveList.push(directives[key])
})

if (window.Vue) {
  Object.keys(directives).forEach(key => {
    window[key] = directives[key]
  })
  directiveInstalls.forEach(install => {
    Vue.use(install);
  })
}

export default directiveList

3、在main.js引入全局指令,或在指定vue文件作为局部指令引入

// main.js全局指令
import directives from '@/components/directive'

directives.forEach(directive => {
  Vue.use(directive)
})

你可能感兴趣的:(#,vue学习,vue.js,javascript,前端,directive)