How to implement infinite scroll in my vue js

20,290

Solution 1

Installation:

npm install vue-infinite-scroll --save

Registration in your main.js:

// register globally
var infiniteScroll =  require('vue-infinite-scroll');
Vue.use(infiniteScroll)

// or for a single instance
var infiniteScroll = require('vue-infinite-scroll');
new Vue({
  directives: {infiniteScroll}
})

Your html:

<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
  ...
</div>

You component:

var count = 0;

new Vue({
  el: '#app',
  data: {
    data: [],
    busy: false
  },
  methods: {
    loadMore: function() {
      this.busy = true;

      setTimeout(() => {
        for (var i = 0, j = 10; i < j; i++) {
          this.data.push({ name: count++ });
        }
        this.busy = false;
      }, 1000);
    }
  }
});

Solution 2

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!");
});

Solution 3

I also tried the Vue-infinite-scroll, but it's not working properly when aligning with Vue-router, at least in my code. So I came up with my own solution.

<template>
  <div ref="loadmore" class="infinite-container">
      <!-- the inifite container -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      timer: null,
      // check if is in infinite procees
      busy: false
    }
  },
  methods: {
    infiniteScrollHandler() {
        //check if container's bttom is overflow screen
      let bottomOff =
        this.$refs.loadmore.getBoundingClientRect().bottom - screen.height;
      if (bottomOff < 10 && !this.busy) {
        console.log("loading... " + new Date());
        this.busy = true;
        // do something 
        this.busy = false;
      }
    },
    setIntervalTimer() {
      //check every 500 milliseconds
      this.timer = setInterval(() => {
        this.infiniteScrollHandler();
      }, 500);
    }
  },
  mounted() {
      // set up timer on mounted
    this.setIntervalTimer();
  },
  beforeDestroy() {
      // do not forget clear the interval timer
    clearInterval(this.timer);
  }
};
</script>
Share:
20,290

Related videos on Youtube

masterhunter
Author by

masterhunter

Updated on July 12, 2020

Comments

  • masterhunter
    masterhunter almost 4 years

    I currently learning combining laravel with vue. This page should be fetching post data from server and showing in user timeline. I am successfully get all data and display it. But i want to implement a infinite scroll into it but i had no idea how to do it. i had been tried many different way also not working. Maybe is my knowledge about vue is still fresh. Any suggestion for me?

    Here is my original code :jsfiddle

    Here is code i try to implement infinite scroll with this example .

    jsfiddle 2

    The scrolling symbol is showing but seem like the array did't not passing , the data still appear all in one time.

    Once submitted /feed the server will return array which contain post information. But i don't know how to passing into the list array.

    Returned Array

    In vue enter image description here

    In route enter image description here

    • Amresh Venugopal
      Amresh Venugopal about 7 years
      you need to show what failed/didn't work. :)
  • masterhunter
    masterhunter about 7 years
    i followed your instruction but the infinite scroll still not working. jsfiddle
  • masterhunter
    masterhunter about 7 years
    In my laravel 5.4 reshources/assets/js/app.js has registered with this. require('vue-infinite-scroll'); Vue.use(infiniteScroll) const app = new Vue({ el: '#app', directives: {infiniteScroll}, store });
  • Gabriel Robert
    Gabriel Robert about 7 years
    Check this out! github.com/ElemeFE/vue-infinite-scroll It should help :) @masterhunter
  • Vladd
    Vladd over 6 years
    your missing endOfPage() method
  • Shyam Kumar
    Shyam Kumar about 6 years
    It's really helpful . Do you have idea how to call method on scroll to top? Thanks
  • PirateApp
    PirateApp over 4 years
    does this really need a library
  • Gabriel Robert
    Gabriel Robert over 4 years
    @PirateApp Why not? Take a look at the implementation: github.com/ElemeFE/vue-infinite-scroll/blob/master/src/…
  • Alex Hunter
    Alex Hunter about 4 years
    is there a way to use in reverse order? i mean render the new posts in top chronological order
  • Aslam H
    Aslam H almost 3 years
    this literally just copy paste from vue-infinite-scroll documentation.