Endless Scroll with VueJS and Vue Resources

So, I can’t understand for life how to get the right infinite scroll made with VueJS and the vue resource. My data is loaded using VueJS and vue-resource, but the issue with scrolling and proper processing is the issue.

Does anyone know how to do this? All the attempts that I tried result in a lot of double requests and spam from my repeated request backend.

What I have tried so far:

  • Completing the request for "this. $ Http.get" in the en event listener for window.scroll and a conditional value inside that that checks if the bottom of the page has reached. This will double or even trigger the get request instead of a single trigger, and then wait for the load to load again.

  • Doing something similar, but with an element at the very bottom of the list, where I would check if it was in sight. Same as using multiple triggers.

+4
source share
1 answer

One solution would be to set up a locking mechanism to stop quick requests to your server. The lock will be enabled before the request is executed, and then the lock will be disabled when the request is completed and the DOM will be updated with 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;
        });
      };
    });
  };
});

, , , scroll , ( ), . 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!");
});

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

+4

Source: https://habr.com/ru/post/1613472/


All Articles