当前位置:首页 > VUE

vue实现防抖节流

2026-01-07 03:31:15VUE

Vue 中实现防抖(Debounce)

防抖的核心是延迟执行函数,在连续触发时取消前一次的调用,只执行最后一次。适用于输入框搜索、窗口大小调整等场景。

方法1:使用 Lodash 的 _.debounce 安装 Lodash 并导入 debounce 方法:

npm install lodash

在 Vue 组件中使用:

vue实现防抖节流

import { debounce } from 'lodash';

export default {
  methods: {
    handleInput: debounce(function(event) {
      console.log('防抖处理:', event.target.value);
    }, 500)
  }
}

方法2:手动实现防抖 通过 setTimeout 和 clearTimeout 实现:

export default {
  data() {
    return {
      timeout: null
    };
  },
  methods: {
    handleInput(event) {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        console.log('防抖处理:', event.target.value);
      }, 500);
    }
  }
}

Vue 中实现节流(Throttle)

节流的核心是限制函数执行频率,在指定时间内只执行一次。适用于滚动事件、频繁点击按钮等场景。

vue实现防抖节流

方法1:使用 Lodash 的 _.throttle

import { throttle } from 'lodash';

export default {
  methods: {
    handleScroll: throttle(function() {
      console.log('节流处理滚动事件');
    }, 1000)
  }
}

方法2:手动实现节流 通过时间戳判断是否执行:

export default {
  data() {
    return {
      lastExecTime: 0
    };
  },
  methods: {
    handleClick() {
      const now = Date.now();
      if (now - this.lastExecTime >= 1000) {
        console.log('节流处理点击');
        this.lastExecTime = now;
      }
    }
  }
}

在模板中的直接使用

通过指令或事件绑定直接调用防抖/节流方法:

<template>
  <input @input="handleInput" />
  <button @click="handleClick">提交</button>
</template>

注意事项

  • 组件销毁时清除定时器:避免内存泄漏,在 beforeDestroy 生命周期中清除未执行的定时器。
  • Vue 3 的 Composition API:可以通过 refonUnmounted 实现更简洁的逻辑。
  • 性能权衡:防抖的延迟时间和节流的间隔需根据实际场景调整。

标签: 防抖vue
分享给朋友:

相关文章

vue实现a

vue实现a

Vue 实现 A 功能的方法 在 Vue 中实现 A 功能可以通过多种方式,具体取决于 A 功能的具体需求。以下是几种常见的实现方法: 使用 Vue 组件 通过创建自定义组件来实现 A 功能。组件可…

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue实现 hover

vue实现 hover

实现 Vue 中的 hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是常见的几种方法: 使用 CSS 伪类 最简单的方式是直接使用 CSS 的 :hover 伪类,无…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…

vue实现列表

vue实现列表

Vue 实现列表的方法 在 Vue 中实现列表渲染通常使用 v-for 指令,可以动态生成多个元素。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 遍历数组,生成列表项。v-for 需要…