Vue3+TS封装全局按钮防抖函数

在Vue3 + TS项目中,我们经常需要对一些按钮进行防抖处理,以避免用户频繁点击而导致的性能问题。因此,我们可以封装一个全局的按钮防抖函数来简化代码,提高开发效率。

实现步骤

  1. 创建 src/utils/debounce.ts 文件。

  2. debounce.ts 文件中,引入 lodash 库,并编写防抖函数。

    import _ from 'lodash';
    
    export function debounce<T extends (...args: any[]) => any>(
      fn: T,
      delay: number = 300
    ): T {
          
          
      return _.debounce(fn, delay, {
          
           leading: true, trailing: false }) as T;
    }
    
    
  3. src/main.ts 文件中,将防抖函数挂载到 Vue 实例的原型上,以便在全局使用。

    import {
          
           createApp } from 'vue';
    import App from './App.vue';
    import {
          
           debounce } from './utils/debounce';
    
    const app = createApp(App);
    
    app.config.globalProperties.$debounce = debounce;
    
    app.mount('#app');
    
    
  4. 在页面中使用 $debounce 函数进行按钮防抖。

    <template>
      <button @click="$debounce(() => handleClick(), 500)">点击</button>
    </template>
    
    <script lang="ts">
    import {
          
           defineComponent } from 'vue';
    
    export default defineComponent({
          
          
      methods: {
          
          
        handleClick() {
          
          
          console.log('按钮被点击了');
        },
      },
    });
    </script>
    
    

总结

通过以上步骤,我们便可以在 Vue3 + TS 项目中快速实现全局按钮防抖函数,提高代码的复用性和开发效率。

猜你喜欢

转载自blog.csdn.net/qq_27244301/article/details/131454287