我在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>
好的,我现在有解决办法了。我的同伴说省略
() =>
可以解决,加上{ trailing: false }
更好。
const handleClick = _.throttle(function () { console.log('hi'); }, 2000, { trailing: false });
您缺少通过添加
()
来运行节流功能:
const handleClick = () =>
_.throttle(function () {
console.log('hi');
}, 2000)();
或将其分配给变量然后运行它:
const handleClick = () =>{
let throttled= _.throttle(function () {
console.log('hi');
}, 2000);
throttled();
}
我尝试实现一个生成包装器的函数,以支持
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)
}
}
}