DEV Community

Cover image for How To Add Infinite Scrolling / Loading to Nuxt?
Gerd
Gerd

Posted on

How To Add Infinite Scrolling / Loading to Nuxt?

Add infinite loading to your Nuxt project in 10 minutes!

Are you tired of using pagination on your site or application? Is it really the best design approach for the end user of your page or
application? There is an alternative that is being used more and more. It's referred to or called
infinite scrolling or infinite loading. If your familiar with lazy loading for images this is the same
concept except for data like a JSON return from a rest API.

Infinite loading is great for sites or applications that return and display lots of data on a single page.
Rather than using pagination where the user has to click on a number button at the bottom of the page to
get more data results, we can implement infinite loading and do away with pagination.

So let's get started!

At this point I'm assuming you have a Nuxt project up and running and are familiar with working in Nuxt.
First we need to install this great Vue plugin called Vue-Infinite-Loading. You can find it
here. https://peachscript.github.io/vue-infinite-loading/ It has very good documentation if you need to
configure additional options for your particular project.

First we need to install the plugin via NPM or YARN, whichever your using, again I'm making the
assumption you know how to use NPM or Yarn.

    npm install vue-infinite-loading -S
Enter fullscreen mode Exit fullscreen mode

Once you have it installed, create a file called in your plugins folder and name it "infiniteloading.js". If you don't yet have a plugins folder, create one.
Let's add the the following code to this file. Here we're importing and registering the component.

import Vue from 'vue'
import InfiniteLoading from 'vue-infinite-loading'
Vue.component('infinite-loading', InfiniteLoading)
Enter fullscreen mode Exit fullscreen mode

Next let's open up the nuxt.config.js file. Find the the plugins array in the file and add the following object.

plugins:[
  { src: '~/plugins/infiniteloading', ssr: false }
]
Enter fullscreen mode Exit fullscreen mode

Well that was easy right? At this point the Infinite Loading component is set up and read to go.
Below is an example of how you would add the component to your page or component.

<infinite-loading spinner="spiral" @infinite="infiniteScroll"></infinite-loading>
Enter fullscreen mode Exit fullscreen mode

Now to test the component let's create a new page in the pages folder and call it infinite-load.vue.
Copy and paste the following code below onto the page and save.

This is an example of using the plugin to get some fake blog posts
from jsonplaceholder.typicode.com/

https://jsonplaceholder.typicode.com/photos?_page=

<template>
  <div style="max-width:800px; margin:auto">
    <div v-for="(item, index) of items" :key="index" style="background:cornflowerblue; color:#eee; border:1px solid #CCC; padding: 1.5rem; margin:.5rem 0; border-radius: 10px;">
      <div class="py-2">{{ item.title }}</div>
    </div>

    <infinite-loading v-if="items.length" spinner="bubbles" @infinite="infiniteScroll"></infinite-loading>
  </div>
</template>


<script>
import axios from "axios";

export default {
  name: "Posts",
  data() {
    return {
      items: [],
      page: 1
    };
  },
  computed: {
    url() {
      return "https://jsonplaceholder.typicode.com/photos?_page=" + this.page;
    }
  },
  created() {
    this.getPhotos();
  },

  methods: {
    async getPhot0s() {
      const resp = await axios.get(this.url);
      this.items = resp.data;
      //console.log(this.items)
    },
    infiniteScroll($state) {
      setTimeout(() => {
        this.page++; // next page
        axios.get(this.url).then(resp => {
                if (resp.data.length > 1) { // check if any left
                  resp.data.forEach(item => this.items.push(item)); // push it into the items array so we can display the data
                  $state.loaded();
                } else {
                  $state.complete();
                }
          })
          .catch(err => {
            console.log(err);
          });
      }, 500);
    }
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Then navigate to the page in your browser and you should see...

(Bada Boom Bada Bing!)

That's it! Were done.

Obviously you will want to modify the code a bit to match up with the API for your project.

Hopefully this gets you on the right path.

Cheers!

Top comments (2)

Collapse
 
thomas_ph35 profile image
Thomas

Hello, great job, i'm trying this right now, this is just what I was looking for !

Collapse
 
dadobaag profile image
DaDoBaag

Hello, do you know if lazy loaded posts via infinite scroll will be discovered by the Nuxt dynamic route crawler (static site generation)?