自定义指令:封装v-debounce

82 阅读1分钟

自定义指令:封装可重用逻辑(v-debounce 实现)

自定义指令是 Vue3 中用于封装可重用逻辑的工具,例如防抖功能。

以下是如何创建一个防抖指令 v-debounce

import { createApp } from'vue';  
  
const app = createApp({});  
  
// 注册自定义指令v-debounce  
app.directive('debounce', {  
  mounted(el, binding) {  
    let timer;  
    // 给 el 绑定事件,默认 click 事件  
    el.addEventListener(binding.arg || 'click', () => {  
      if (timer) {  
        clearTimeout(timer);  
      }  
      // 回调函数延迟执行  
      timer = setTimeout(() => {  
        binding.value();  
      }, binding.modifiers.time || 300);  
    });  
  }  
});  
  
app.mount('#app');

使用示例:

<template>  
  <!-- 300毫秒内多次点击只会执行一次 -->  
  <button v-debounce:click.time="500" @click="fetchData">请求数据</button>  
</template>  
  
<script setup>  
import { ref } from 'vue';  
  
const fetchData = () => {  
      console.log('执行数据请求');  
    };  
</script>