vue中的防抖和节流

防抖(debounce)是指在事件被触发 n 秒后才执行回调函数,如果在这段时间内再次触发了事件,则重新计时。防抖的主要作用是防止重复提交或重复操作。

引入  npm i --save lodash  网址 Lodash 简介 | Lodash 中文文档 | Lodash 中文网

<template>
  <div>
    <input type="text" v-model="searchQuery" @input="handleInput" />
  </div>
</template>

<script>
import { debounce } from 'lodash'

export default {
  data() {
    return {
      searchQuery: ''
    }
  },
  methods: {
    handleInput: debounce(function() {
      console.log('输入完成')
      // 在这里添加处理输入的逻辑
    }, 500)
  }
}
</script>

使用自定义指令 实现防抖

<template>
  <div>
    <input type="text" v-model="keyword" v-debounce-input="handleDebouncedInput" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
    }
  },
  methods: {
    // 在这里添加处理输入事件的逻辑
    handleDebouncedInput(keyword) {
      console.log('防抖回调函数', keyword)
    }
  },
  directives: {
    // 自定义指令实现防抖
    debounceInput: {
      inserted: function(el, binding) {
        let debounceTime = binding.arg || 500
        let debounceFn = _.debounce(function() {
          binding.value(el.value)
        }, debounceTime)
        el.addEventListener('input', debounceFn)
      }
    }
  }
}
</script>

vue中使用手写防抖

<template>
  <div>
    <input type="text" v-model="inputValue" @input="handleDebouncedInput" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: "",
      timeoutId: null,
    };
  },
  methods: {
    handleDebouncedInput() {
      clearTimeout(this.timeoutId);
      this.timeoutId = setTimeout(() => {
        this.doSomethingWithInput(this.inputValue);
      }, 500); // 设置延迟时间为 500 毫秒
    },
    doSomethingWithInput(inputValue) {
      console.log("Debounced input:", inputValue);
      // 在这里进行具体的操作
    },
  },
};
</script>

 vue中的throttle

<template>
  <div>
    <input type="text" v-model="inputValue" @input="handleThrottledInput" />
  </div>
</template>

<script>
import { throttle } from "./utils";

export default {
  data() {
    return {
      inputValue: "",
    };
  },
  methods: {
    handleThrottledInput: throttle(function() {
      console.log("Throttled input:", this.inputValue);
      // 在这里进行具体的操作
    }, 500), // 设置延迟时间为 500 毫秒
  },
};
</script>

函数节流

function throttle(func, delay) {
  let prevTime = 0;
  return function() {
    const context = this;
    const args = arguments;
    const currTime = Date.now();
    if (currTime - prevTime > delay) {
      func.apply(context, args);
      prevTime = currTime;
    }
  };
}

 它接受两个参数:一个是要执行的函数 func,另一个是节流的时间间隔 delay。当调用返回的函数时,它会检查当前时间与上一次调用的时间间隔是否超过了节流的时间间隔,如果超过了,则执行传入的函数 func,否则不执行。

 vue中使用节流的自定义指令  针对于点击按钮的效果

<template>
  <button v-throttle-click="handleClick">Click me</button>
</template>

<script>
export default {
  directives: {
    'throttle-click': {
      bind: function (el, binding) {
        const delay = parseInt(binding.arg) || 1000; // 获取节流延迟时间,如果未传递参数,则默认为1秒
        let timeout = null;

        function handleClick() {
          if (timeout) {
            clearTimeout(timeout);
          }

          timeout = setTimeout(() => {
            binding.value.call(this);
          }, delay);
        }

        el.addEventListener('click', handleClick);
      }
    }
  },
  methods: {
    handleClick() {
      console.log('Clicked!');
    }
  }
}
</script>

//还可以  定义时间
<button v-throttle-click:500="handleClick">Click me</button>

vue中使用库点击按钮节流

import { throttle } from 'lodash';

export default {
  methods: {
    handleClick: throttle(function() {
      console.log('Button clicked!');
    }, 1000)
  }
}

在上面的代码中,throttle 函数接受两个参数:真正的点击事件处理函数和一个时间间隔,单位为毫秒。throttle 函数将返回一个新的函数,这个函数将在指定的时间间隔内最多执行一次真正的点击事件处理函数。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue防抖节流都是常见的应用技巧。 防抖的应用场景是在连续触发事件后,在一定的时间间隔内只执行一次函数。这在处理一些频繁触发事件的情况下非常有用,比如输入框输入时的实时搜索功能。通过使用防抖,可以避免频繁触发搜索请求,提高性能和用户体验。在Vue,可以使用定时器版的防抖方式来实现,即通过设置一个定时器,在规定的时间内未再次触发事件时执行函数。代码示例如下: ```javascript // 在Vue组件 data() { return { timer: null // 定时器变量 } }, methods: { debounceFunc() { if (this.timer) { clearTimeout(this.timer); // 清除之前的定时器 } this.timer = setTimeout(() => { // 执行函数 // 代码 }, 1000); // 设置延迟时间 } } ``` 节流的应用场景是在连续触发事件时,在一定的时间间隔内只执行一次函数。与防抖不同的是,节流是按照一定的时间间隔执行函数,而不是在固定的时间间隔后执行。节流常用于减少频繁触发事件时的计算或请求次数,比如页面滚动时的加载更多功能。在Vue,可以使用时间戳版的节流方式来实现,即通过记录上次执行函数的时间戳,在规定的时间间隔后执行函数。代码示例如下: ```javascript // 在Vue组件 data() { return { lastTime: 0 // 上次执行函数的时间戳 } }, methods: { throttleFunc() { const now = Date.now(); // 当前时间戳 if (now - this.lastTime > 1000) { // 间隔时间大于1秒,执行函数 // 代码 this.lastTime = now; // 更新上次执行函数的时间戳 } } } ``` 综上所述,在Vue可以通过防抖节流来优化一些频繁触发事件的情况,提高性能和用户体验。具体的应用场景和方式可以根据实际需求来选择和实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue防抖节流的使用](https://blog.csdn.net/qq_35191845/article/details/123668054)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_2524963996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值