简体   繁体   中英

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

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),
  }
}

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

    <script>
       export default {
          methods: {
             delay: _.debounce(function() {
               //code
             }, 700),
          }
        }
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM