Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite scroll with VueJS and vue-resource

So, I can't for the life of me figure out how to get a proper infinite scroll done with VueJS and vue-resource. My data is loading with VueJS and vue-resource, but the trigger on scroll and proper handling is the issue.

Does anybody know how to do this? All attempts I tried lead to loads of double requests and spamming my backend with repeat requests.

What I've tried so far:

  • Wrapping the "this.$http.get" request into a en event listener for window.scroll and a conditional within that, which checks if the bottom of the page is reached. This would alway double or even multi-trigger the get request instead of just one trigger and then waiting for load again.

  • Doing something similar but with an element at the very bottom of the list where I would check if it was in view. The same thing with multi-triggering get requests.

like image 847
barfurth Avatar asked Sep 26 '22 09:09

barfurth


1 Answers

One solution would be to setup a locking mechanism to stop rapid requests to your backend. The lock would be enabled before a request is made, and then the lock would be disabled when the request has been completed and the DOM has been updated with the new content (which extends the size of your page).

For example:

new Vue({
  // ... your Vue options.

  ready: function () {
    var vm = this;
    var lock = true;
    window.addEventListener('scroll', function () {
      if (endOfPage() && lock) {
        vm.$http.get('/myBackendUrl').then(function(response) {
          vm.myItems.push(response.data);
          lock = false;
        });
      };
    });
  };
});

Another thing to keep in mind is that the scroll event is triggered more than you really need it to (especially on mobile devices), and you can throttle this event for improved performance. This can efficiently be done with requestAnimationFrame:

;(function() {
    var throttle = function(type, name, obj) {
        obj = obj || window;
        var running = false;
        var func = function() {
            if (running) { return; }
            running = true;
            requestAnimationFrame(function() {
                obj.dispatchEvent(new CustomEvent(name));
                running = false;
            });
        };
        obj.addEventListener(type, func);
    };

    /* init - you can init any event */
    throttle ("scroll", "optimizedScroll");
})();

// handle event
window.addEventListener("optimizedScroll", function() {
    console.log("Resource conscious scroll callback!");
});

Source: https://developer.mozilla.org/en-US/docs/Web/Events/scroll#Example

like image 117
Amir Rustamzadeh Avatar answered Sep 30 '22 06:09

Amir Rustamzadeh