Pagination in Vue.js (Part 1)

Iboro Inyang
3 min readMay 12, 2022

--

One thing that has helped me make a smooth transition from Vue.js2 (which uses Options API) to Vue.js3 (which uses Composition API) is learning the similarities between the two before moving on the understanding the new perks added in the new version.

So I’ve built a very simple app using Vue.js 2 and the exact same app in Vue.js 3 just to help smooth the transition for those learning to grasp it. The focus of the app is to implement a common feature in most webpages, Pagination, we’ll be seeing the variations in implementations in Vue.js 2 and Vue.js 3.

So the app is a simple picture gallery, we’ll be using a random image generator, Lorem-picsum to get a bunch of random images, it’s free and easy and requires no sign-up. In order to implement this, we’ll be making use the axios library for network requests. As seen in the code snippet below, we are making the network request at the point the component is mounted and storing it in the allImages array.

For the script section, we have a singlePage variable where we’d be storing adn looping through the data(list of images) for that page. The only computed property we’d need is the numberOfPages, based on the total images available and how many items we want to display per page.

We keep track of the currentPage to avoid any confusion and the actual logic for navigating to any page is in the goToPage function, made possible by little math calculations and little Javascript array helper methods.

Now if we had static data, we could simply call goToPage(1) immediately the page loads but since we’re working with dynamic data gotten from an API, for the pagination to actually kick when we need it to, we need to track when the data is actually ready and call it then. Either by calling it in the then hook of our API call or alternatively using a watcher to track the arrival of the data.

Either of these methods would work fine
Code Snippet

The HTML template is as seen above; we added the nextPage and prevPage functions to the back and previous buttons and also made the arrow dynamic so they don’t show when not needed. Like I said earlier, and as seen above, we’re looping through the singlePage variable cause that holds a single page which we need at every point.

This looks great so far, the final output would look something like this. I haven’t really paid much attention to styling thus far, you can style however you wish. Like I said at the start of the article, I’ll be building the exact same app again using Vue3 just to compare the similarities and try out the new features.

Thanks so much for sticking with me till the end. I’ll see you again in a bit.
Cheers!

--

--