How to Set Up Pagination in Gridsome
Linda
Posted on February 15, 2021
What is Gridsome
Gridsome is a modern website development framework for creating fast and secure websites that can be deployed anywhere. Static HTML files are generated to create SEO-friendly markup that hydrates into a Vue.js-powered SPA once loaded in the browser. Gridsome has also made it easier than ever before to set up pagination π
Steps to set up Gridsome Pagination
I am assuming that you already have a Gridsome blog that fetches blog posts and you are adding pagination as a new feature. In that case, these are the steps to follow.
- Setup Pagination in GraphQL query
- Import Gridsome's Pager component
- Add necessary styling
Setup Pagination in GraphQL query
Data collection is handled by the GraphQL query in Gridsome. We can use the @paginate directive in the GraphQL query to add automatic pagination for a collection.
The query will receive a $page: Int variable you can use to load sources for a specific page.
query ($page: Int) {
allBlogPost(perPage: 10, page: $page) @paginate {
pageInfo {
totalPages
currentPage
}
edges {
node {
id
title
path
}
}
}
}
In the example above, each page will contain 10 blog posts.
Import Gridsome's Pager component
Gridsome has a built-in Pager component which can be imported for easy pagination. Import and add the Pager component from Gridsome.
import { Pager } from 'gridsome';
export default {
components: {
Pager
}
}
Though the Pager component can accept multiple properties, the only required properties are "total number of Pages" and "current Page". These properties can be found in "pageInfo" which we pass into the Pager component.
<Pager :info="$page.allBlogPost.pageInfo" />
Add Custom Styles
We can style the pagination container using normal CSS classes but need to use the :linkClass property to style the links.
Template
<Pager :info="$page.allBlogPost.pageInfo"
class="pager-container"
linkClass="pager-container__link" />
Styles
<style scoped lang="scss">
.pager-container {
display: inline-block;
font-size: 1.5rem;
text-align: center;
width: 100%;
color: black;
&__link {
text-align: center;
padding: 0.6rem 1.2rem;
color: white;
text-decoration: none;
}
}
.active {
background-color: rgb(44, 201, 180);
}
</style>
That's all folk. I have been writing consistently for 4 months ππ
You might also enjoy my article on How to add Code snippets to Gridsome
Posted on February 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 4, 2023