Categories
Vue

Add Infinite Scrolling to a Vue App with vue-infinite-scroll

Spread the love

Infinite scrolling is where the user can keep scrolling to get new data and append it to the bottom of the page.

In this article, we’ll look at how to add infinite scrolling to a Vue app with the vue-infinite-scroll plugin.

Install

We can install it by running:

npm install vue-infinite-scroll --save

Usage

After installing it, we can use it.

First, we register the plugin in main.js :

import Vue from "vue";
import App from "./App.vue";
import infiniteScroll from "vue-infinite-scroll";
Vue.use(infiniteScroll);
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App)
}).$mount("#app");

This registers it globally.

We can also register it locally by writing:

import infiniteScroll from 'vue-infinite-scroll'
new Vue({
  directives: {infiniteScroll}
})

Then we can use it bu writing:

<template>
  <div id="app">
    <div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
      <div v-for="n in num" :key="n">
        <img :src="`https://picsum.photos/id/${n}/300/150`">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      num: 10,
      busy: false
    };
  },
  methods: {
    loadMore() {
      this.busy = true;
      setTimeout(() => {
        this.num += 50;
        this.busy = false;
      }, 1000);
    }
  }
};
</script>

The v-infinite-scroll directive makes the div become an infinite scrolling container.

We set it to the loadMore method so that we move.

infinite-scroll-distance is the distance in percentage relative to the bottom of the screen.

The loadMore method will run we scroll the screen within the distance of the screen.

infinite-scroll-disabled lets us disabling infinite scrolling when some condition is true .

We display infinite scrolling when we’re loading more data.

Conclusion

We can add infinite scrolling to a Vue app with the vue-infinite-scroll plugin.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *