vue全局注册自定义指令

298 阅读1分钟

创建一个directive/index.js文件统一管理

防抖指令,可用于表单提交防止重复点击

export default vue => {
  vue.directive('debounce', {
    inserted: (el, binding) => {
      let timer;
      el.addEventListener('click', () => {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          binding.value();
        }, 400);
      });
    },
  });
};

在main.js中导入

import Directive from '@/directive';
Directive(Vue);

使用示例

  <button type="primary" v-debounce="onSubmit">搜索</-button>