How To Implement an Infinite Scroll with Vue and Nuxt
Infinite scrolling is a feature on websites and applications where a user scrolls down and reaches the bottom of the current page of content and then the next page of content is loaded and displayed digital ocean.
My API response look like this, built on django rest -
And now I want to increase the page number and send request for next page result and merge data with my initial data object when user go bottom of page.
data() {
return {
productObj:[],
rawObj:[],
page:1,
}
},
mounted() {
this.scroll()
},
async fetch() {
await this.fetchData()
},
methods:{
scroll () {
window.onscroll = () => {
let bottomOfWindow = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop) + window.innerHeight === document.documentElement.offsetHeight
if (bottomOfWindow) {
this.page++
if(this.rawObj.next){
this.fetchData()
}
}
}
},
async fetchData(){
try{
const res = await this.$axios.$get(`productByPagination/?page=${this.page}`)
this.productObj.push(...res.results)
this.rawObj = res
}
catch({response}){
console.log(response)
}
},
}
Explanation
In first position I set page number 1 in data and send make initial request for storing 1st page data. Then scroll method is responsible when user goes bottom of page it will increase page number and send request to load second page data.
let bottomOfWindow = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop) + window.innerHeight === document.documentElement.offsetHeight
bottomOfWindow
return true if user go bottom of the page. And if we get true then this piece of code will execute-
if (bottomOfWindow) {
this.page++
if(this.rawObj.next){
this.fetchData()
}
}
Note
In productObj:[],
I stored only my desire result and in rawObj:[],
I stored total response object. And in rawObj has next
which help us to understand is their available any data. If available send another request or make stopped from send another request.
Situation can be different in different API response.