简体   繁体   中英

Vue.js debounce scroll

I am trying to use the debounce package with a Vue.js v-on:scroll binding like so:

<div @scroll="debounce(onScrollMessages, 200)"></div>

The problem is that debounce actually returns the debounced function to be used, but binding the event this way will actually call debounce(onScrollMessages, 200) every scroll event, this means that the debounced function will be computed and created every scroll event.

The actual issue is that the @scroll will bind the event something like this:

onScroll: function () {
   debounce(onScrollMessages, 200);
}

But, in order for the debounced function to be computed only once it should bind the event something like this:

// Notice how now the scroll event calls directly the 
// debounced function returned by "debounce()", not the
// function that calls "debounce()"
onScroll: debounce(onScrollMessages, 200)

How can I bind the @scroll event to the function returned by debounce() and not to a function that calls debounce() every time?

I actually figured out the solution right after asking this question.

Before I was declaring the debounce function like so (just aliasing it so I have access to it inside the template):

methods: {
   debounce: debounceFromNPM
}

But I changed it to this and it works (don't alias the package "debounce", but the returned debounced function directly):

debounce: debounceFromNPM(function () {
  this.onScrollMessages();
}, 3000)

And changed the template to:

<div @scroll="debounce"></div>

Notice that if you are using ES6 arrow function syntax, having the lexical this it won't work:

// THIS DOESN'T WORK AS `this` WILL BE UNDEFINED
debounce: debounceFromNPM(() => {
  this.onScrollMessages();
}, 3000)

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