在 Vue 3 中使用节流阀

问题描述 投票:0回答:3

我在Vue 3项目中使用lodash,当我尝试在

_.throttle
函数中使用
setup
时,它不起作用。我在stackblitz中写了一个演示。

<template>
  <div id="app">
    <button @click="handleClick">Click</button>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'App',
  setup() {
    const handleClick = () =>
      _.throttle(function () {
        console.log('hi');
      }, 2000);

    return {
      handleClick,
    };
  },
};
</script>

vue.js lodash vuejs3 vue-composition-api
3个回答
2
投票

好的,我现在有解决办法了。我的同伴说省略

() => 
可以解决,加上
{ trailing: false }
更好。

const handleClick = _.throttle(function () { console.log('hi'); }, 2000, { trailing: false });


0
投票

您缺少通过添加

()
来运行节流功能:

  const handleClick = () =>
      _.throttle(function () {
        console.log('hi');
      }, 2000)();

或将其分配给变量然后运行它:

  const handleClick = () =>{
     let throttled= _.throttle(function () {
        console.log('hi');
      }, 2000);
     
     throttled();
   }


0
投票

我尝试实现一个生成包装器的函数,以支持

Throttle
Debounce
TS 中的函数,无需其他库。

export function useThrottleFn<T extends any[]>(fn: Function, wait: number): (...args: T) => void {
  let timer: any
  return (...args: T) => {
    if (!timer) {
      fn(...args)
      timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
      }, wait)
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.