有时候我们表单保存时,如果快速点击保存按钮,会出现多次提交保存同一表单到数据库的问题,这样会导致同一表单短时间重复提交多次,于是我们可以用到防抖。
在Vue项目里,找到src下的directives目录,如果发现src下没有这个目录,那我们就自己建一个directives目录。然后directives目录下新建一个index.js和debounce.js,这个index.js里就是引入和注册我们的自定义指令,如下所示:
//index.js
import debounce from './debounce' //防抖
// 自定义指令
const directives = {
debounce,
}
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key])
})
},
}
//debounce.js
const debounce = {
inserted: function (el, binding) {
let timer
el.addEventListener('click', () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
binding.value()
}, 3000)
})
},
}
export default debounce
最后在入口文件main.js里引入自定义指令
//main.js
//引入自定义指令
import Directives from './directives/index.js'
Vue.use(Directives)
然后在我们组件里这样使用,我们以前写点击事件是@click=“事件名”,现在就是v-debounce=“事件名”,如下图:
如果说这个点击事件需要传参数,那我们需要一个中转的方法,如下图,我们点击保存,实际需要调用submit方法保存,先通过submitClick中转去调用submit,然后再通过submit传参:
这是因为我们自定义指令里是binding.value( )直接使指令调用的是方法,具体在自定义指令里如何传参,目前我只想到了这种中转方法,有知道的小伙伴可以相互交流。