Home > Net >  Using throttle with Vue 3
Using throttle with Vue 3

Time:10-26

I use lodash in a Vue 3 project, when I try to use the _.throttle in the setup function, it doesn't work. I writed a demo in the 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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You're missing to run the throttled function by adding the () :

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

or assign it to a variable then run it :

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

CodePudding user response:

Okay, I have a solution now. My companion said that omit the () => can fix it, add the { trailing: false } is better.

const handleClick = _.throttle(function () { console.log('hi'); }, 2000, { trailing: false });
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related