1

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(...) ?

kissu
  • 40,416
  • 14
  • 65
  • 133
Sam
  • 2,275
  • 9
  • 30
  • 53
  • My guess is that `this` in your case does not refer to the vue prototype. Can you post the surrounding code? – net.uk.sweet Apr 22 '21 at 08:15
  • judging by the 'delay' key, you are in an object which changes the context of 'this', post the entire code so we can know for sure. – itay_alon Apr 22 '21 at 08:16
  • Here, you will load the entire `lodash` library in your bundle, hence my solution which will only import the needed function. – kissu Apr 22 '21 at 08:20
  • net.uk.sweet, itay_alon i edited the post, the delay function is in methods section. – Sam Apr 22 '21 at 10:00

2 Answers2

2

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

kissu
  • 40,416
  • 14
  • 65
  • 133
  • As i have already imported the lodash package in main.js, is there any way that i can use it from there? – Sam Apr 22 '21 at 10:18
  • 1
    Not sure about the issue here but you could also use `import debounce from 'lodash/debounce'`, the bundle size will be small too. – kissu Apr 22 '21 at 12:26
2

Try this out. For me it worked as _.debounce as shown below:

    <script>
       export default {
          methods: {
             delay: _.debounce(function() {
               //code
             }, 700),
          }
        }
    </script>
Saniya syed qureshi
  • 3,053
  • 3
  • 16
  • 22