Vue中的全局指令防止按鈕重復點擊
全局指令防止按鈕重復點擊
1.common.js
首先引入Vue
import Vue from 'vue'; const preventReClick = Vue.directive('preventReClick', { inserted: function (el, binding) { el.addEventListener('click', () => { if (!el.disabled) { el.disabled = true setTimeout(() => { el.disabled = false }, binding.value || 3000) } console.log(el.disabled) }) } }); export { preventReClick }
2.在需要引入的頁面引入(**.vue)
在按鈕上添加v-preventReClick
<el-button size="small" type="primary" @click="handleSave('form')" v-preventReClick>確定</el-button>
從common.js導入指令preventReClick
import preventReClick from '../common' //防多次點擊,重復提交
防重復點擊(vue指令實現)
阻止快速點擊按鈕會重復多次調用接口的
定義全局指令
// directive.js export default { install (Vue) { // 防重復點擊(指令實現) Vue.directive('repeatClick', { inserted (el, binding) { el.addEventListener('click', () => { if (!el.disabled) { el.disabled = true setTimeout(() => { el.disabled = false }, binding.value || 1000) } }) } }) } }
在main.js引用
import directive from 'directive.js'; vue.use(directive );
按鈕調用直接加v-preventReClick
<el-button v-repeatClick type="prismary" style="width:100%;" @click="handleSubmit"></el-button>
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。