第一步、在src目录下新建directives文件文件夹
用来存放不同的指令,以dbounce指令为例:

第二步、在directives目录下创建debounce.js文件,文件内容如下:
- // 防抖
- const debounceClick = {
- mounted(el, binding) {
- let timer
- el.addEventListener('click', () => {
- if (timer) {
- clearTimeout(timer)
- }
- timer = setTimeout(() => {
- binding.value.fn()
- }, binding.value.time)
- })
- }
- }
- export default debounceClick;
第三步、在directives目录下创建index.js文件,文件内容如下:
- import debounceClick from "./debounce"; // 引入需要的指令
-
- const directivesList = {
- debounceClick // 挂载 ,这里防抖指令的名字不要定义为debounce,否则不生效,原因暂未找到,欢迎大神留言指导
- };
-
- const directives = {
- install: function (app) {
- Object.keys(directivesList).forEach((key) => {
- app.directive(key, directivesList[key]); // 注册
- });
- }
- };
-
- export default directives;// 抛出
第四步、在main.js中引入注册
- import { createApp } from 'vue'
- import App from './App.vue'
- import Directives from '@/directives/index'
- const app = createApp(App)
- app.use(Directives)
- app.mount('#app')
第五步、在模版中使用
- <el-button type="success" plain v-debounceClick="{'fn':openDialog, 'time': 1000}">防抖测试el-button>
-
- <script setup>
- const openDialog = ()=> {
- console.log("防抖函数执行了")
- }
- script>