Skip to content

Instantly share code, notes, and snippets.

@izzygld
Last active May 27, 2022 01:56
Show Gist options
  • Save izzygld/06736aae16a9ab169553d8d411a6de08 to your computer and use it in GitHub Desktop.
Save izzygld/06736aae16a9ab169553d8d411a6de08 to your computer and use it in GitHub Desktop.
Wp Graphql Vue Pagination
1. Regular post query with pagination fields
2. include the Pagination Component
3. The actual pagination.
----------------
1. const postsQuery = gql`
query GetAllPosts ($first: Int, $last: Int, $endCursor: String, $startCursor: String) {
posts(first:$first last:$last after:$endCursor before:$startCursor) {
edges {
node {
title
date
id
slug
excerpt
featuredImage {
node{
sourceUrl
srcSet
altText
id
}
}
}
cursor
}
pageInfo {
hasNextPage
startCursor
endCursor
}
}
}
`
2. <Pagination :posts="posts" :postsQuery="postsQuery" @updatePosts="updatePosts" :limit="10"/>
/*Pagintion Component*/
3. <template>
<div class="pagination">
<a v-if="hasPreviousPage" @click="paginate(-1)" class="prev">← Previous Page</a>
<a v-if="hasNextPage" @click="paginate(+1)" class="next">Next Page →</a>
</div>
</template>
<script>
export default {
name: 'Pagination',
data () {
return {
firstStartCursor: this.posts.data.posts.pageInfo.startCursor,
hasNextPage: this.posts.data.posts.pageInfo.hasNextPage,
hasPreviousPage: false,
first: null,
last: null,
startCursor: null,
endCursor: null
}
},
props: {
posts: {
type: Object
},
postsQuery: {
type: Object
},
limit: {
type: Number
},
where: {
type: Object
}
},
methods: {
async paginate(i){
if (i < 0) {
this.first = null
this.last = this.limit
this.startCursor = this.posts.data.posts.pageInfo.startCursor
this.endCursor = null
} else if (i > 0) {
this.first = this.limit
this.last = null
this.startCursor = null
this.endCursor = this.posts.data.posts.pageInfo.endCursor
}
await this.$apolloProvider.defaultClient
.query({
query: this.postsQuery,
variables: {
first: this.first,
last: this.last,
endCursor: this.endCursor,
startCursor: this.startCursor,
where: this.where
}
}).then((posts) => {
this.$emit('updatePosts', posts)
if (i < 0) {
this.hasNextPage = true
this.hasPreviousPage = (this.firstStartCursor == posts.data.posts.pageInfo.startCursor ? false : true)
} else {
this.hasPreviousPage = true
this.hasNextPage = posts.data.posts.pageInfo.hasNextPage
}
})
window.scroll({ top:0, left:0, behavior:'smooth' });
}
}
};
</script>
<style scoped>
.pagination{
display: flex;
margin: 15px auto 0px;
max-width: 900px;
padding: 0 10px;
a:hover{
cursor: pointer;
color: #4b7bdf;
}
}
.next{
margin-left: auto;
}
</style>
@idesignzone
Copy link

idesignzone commented Aug 10, 2021

I create a repo for Gridsome and WPGraphQL. https://github.com/idesignzone/gridsome-minimum.git.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment