Infinite Scroll in Nuxt.js

For adding the Load More functionality in the nuxt js you need to install the Vue-infinite-loading here with npm

	npm install vue-infinite-loading -S

Then you need to import this package in your post file like posts.vue file. Make sure you have installed the Axios

	import axios from 'axios'
	import InfiniteLoading from 'vue-infinite-loading'

Now your setup is ready you need to add the code on the bottom of the posts.vue file

<infinite-loading 
 v-if="posts.length" 
   spinner="spiral"
   @infinite="infiniteScroll"
></infinite-loading>

posts.length is the post array in which all the posts are store.

Then copy and paste the below code on the method functionality

	infiniteScroll($state) {				
				setTimeout(() => {
					this.page++					
					axios
					.get(this.url)
					.then((response) => {						
						if (response.data.posts.length > 1) {
							response.data.posts.forEach((item) => this.posts.push(item))
							$state.loaded()							
							} else {							
							$state.complete()
							}
					})
					.catch((err) => {
						console.log(err)
					})
				}, 1000)
			}

setTimeout is for to call the code a little bit late.

axios.get is getting the data from the api.

response.data.posts.length is to check whether it’s getting data, if there is no data it will be false.

response.data.posts.forEach((item) => this.posts.push(item)) is adding every new item from array to the posts

$state.loaded(),$state.complete() is the animation of loading the component.

Complete script code

><script>
	
	import axios from 'axios'
	import InfiniteLoading from 'vue-infinite-loading'
	export default {
		name: 'Posts',		
		data() {
			return {
				posts: [],
				page: 1				
			}
		},
		computed: {
			url() {				
				return 'Paste your API URL here'
			}
		},
		created() {
			this.fetchData()
		},  
		methods: {
			async fetchData() {
				const response = await axios.get(this.url)
				this.posts = response.data.posts	 
			},
			infiniteScroll($state) {				
				setTimeout(() => {
					this.page++					
					axios
					.get(this.url)
					.then((response) => {						
						if (response.data.posts.length > 1) {
							response.data.posts.forEach((item) => this.posts.push(item))
							$state.loaded()							
							} else {							
							$state.complete()
							}
					})
					.catch((err) => {
						console.log(err)
					})
				}, 1000)
			}
		},
		components: {
			InfiniteLoading
		}
	}
></script>

On: 02-16-2020