Search code examples
javascriptvue.jslodash

Vue - How to use lodash debounce


I am using debounce from lodash which is imported in main.js

import lodash from 'lodash'
Vue.prototype._ = lodash

And I am using like this._.find(...), it's all working fine. But if i use debounce it is not working.

<script>
   export default {
      methods: {
        delay: this._.debounce(function () {
         // Code
        }, 500),
      }
    }
</script>

It throws this error Uncaught TypeError: Cannot read property 'debounce' of undefined

What could be the right way to use the this._.debounce(...) ?


Solution

  • This should work

    <script>
    import { debounce } from 'lodash-es' // optimized es6-import package, similar to usual 'lodash'
    
    export default {
      methods: {
        yourCoolFunction: debounce(function (event) { // event is the object parameter given to 'yourCoolFunction' if any
          // your tasty code
        }, 500),
      }
    }
    

    And don't forget to add this to the nuxt.config.js file too

    build: {
      transpile: ['lodash-es'],
    }
    

    For more details about what is a debounce, you can check this article: https://redd.one/blog/debounce-vs-throttle