Being a jQuery developer you get serious FOMO by reading all about React, Vue & Angular, I too started learning React, but it kinda had a steep learning curve for me as I did not get enough time to learn this while working full time on weekdays & as a freelancer on weekends.
I purchased a course on Udemy in hopes of learning it one day but it’s left in the dust. Yes, I know how popular React is, but somehow I chose to learn Vue because it was way easier than React, you could understand simply by looking at someone else’s code and get a brief idea on what it is doing & its as simple as adding a script in your HTML head tag and you are good to go, no Webpack, build hassles.
Enough about Vue, lets build a small Project. We will be building a app where we will get data from a REST api and display it on our DOM. It should have infinite scroll enabled.
PS I am still learning vue.js and might have written something in a unusual way.
Lets begin by adding Vue, Axios & Bulma CDNs in out HTML file & I have made a small card displaying a post title & it’s body.
So we need some fake JSON from thisAPI, it will send you around 100 posts in json format, we will use vue & axios to consume this API and display the data in those cards, like above.
We will call the api and store the response in a data variable called posts. We need to get the data as soon as the page is loaded, there’s someting called created()(similar to document.ready in jQuery) on the vuelifecycle, this function will run a function for us as soon as the document is created. Once we have the data with us, we will use v-for directive to loop through this data and create multiple cards like above and display them.
Here you can see that axios has received the data as json and vue’s v-for feature has looped through the array and displayed it.
We have completed our first goal to fetch data from a remote api and display it in our webpage.
There’s a issue with this though, this is a huge list and sometime’s appending a large amount of HTML dynamically to the DOM will lead to lots of issues, think of a old computer or phone and you appended over a 100 rows of data to your webpage, this can crash your browser.
A neat solution here is to use Infinite scroll, this will display the user only a limited amount of rows and shows you more once you hit the bottom of you page.
We will be checking if bottom of screen is visible with a scroll listener function something like this.
Got the idea?
This is one way to do it, but I found a small Vue plugin which does this flawlessly - Vue Infinite Scroll
This even supports integration with a CDN and skips all the build part. Lets add this in our pen from above.
So here we go, we now have consumed a REST api via Axios and displayed it nicely using Vues awesome v-for directive and used the vue infinite scroll plugin to make it even better.
Share if you found this article useful.