Writing pagination from scratch can be tricky at times.
I was recently tasked with writing a pagination component to organize a variety of items on our website. In the process, I found that using slots can be helpful in organizing multiple lists across a website, depending on what you’re trying to do.
Simply put, if you are just writing pagination for a single list in your application, just letting the pagination component handle all the logic works fine.
If you want to reuse the pagination with slots, you need to have the parent component handle a bit of the logic.
Below, you'll see some examples of when and when not to implement slots for pagination.
Without slots
This example uses a card component, but you can replace that with whatever component or item you want rendered within the pagination. This is the template I used in my Pagination.Vue component
Note the v-for is going through a list called displayedItems – which is a computed property. The script is as follows for Pagination.Vue:
To call it from the parent, simply send the list and itemsPerPage as props, and it will handle the rest.
To make use of slots and have the component be reusable across the entire application, there needs to be a bit more logic handled by the parent component wherever it is used.
Move the variables of currentPage and itemsPerPage into the parent, as well as the computed property displayedItems.
Somewhere in the setup of your parent component, you should have this code:
Now, the Pagination component will look like this, with a slot set up to render whatever list you want. Note the difference in props – these will be sent by the parent.
You'll see that we will now emit the change page event to the parent, which will handle the logic.
The rendering from the parent now looks like this
Slots can be useful depending on what you’re aiming to do with your page or application — but don’t be afraid to get creative with your pages and see what works. Happy coding!