Skip to content

Instantly share code, notes, and snippets.

@AliNaraghiA
Created June 24, 2023 05:54
Show Gist options
  • Save AliNaraghiA/9f366a9013ffe78f1e87303e44cb0590 to your computer and use it in GitHub Desktop.
Save AliNaraghiA/9f366a9013ffe78f1e87303e44cb0590 to your computer and use it in GitHub Desktop.
<template>
<div>
<h1>All Posts</h1>
<ul>
<li v-for="post in posts" :key="post.databaseId">
<h2>{{ post.title }}</h2>
<p>{{ post.excerpt }}</p>
<img v-if="post.featuredImage" :src="post.featuredImage.node.sourceUrl" alt="Featured Image" />
</li>
</ul>
<div class="pagination">
<router-link
v-for="page in totalPages"
:key="page"
:to="{ path: '/posts', query: { page: page } }"
:class="{ 'current-page': currentPage === page }"
>
{{ page }}
</router-link>
</div>
</div>
</template>
<style scoped>
.pagination {
display: flex;
justify-content: center;
margin-top: 1rem;
}
.pagination .current-page {
font-weight: bold;
color: blue;
}
</style>
<script>
// pages/posts.vue
import gql from 'graphql-tag'
export default {
// pages/posts.vue
async asyncData({ app, route }) {
const query = gql`
query Posts($first: Int, $after: String, $offset: Int) {
posts(first: $first, after: $after, where: { offsetPagination: { offset: $offset } }) {
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
offsetPagination {
hasMore
hasPrevious
total
}
}
edges {
node {
databaseId
title
slug
excerpt
featuredImage {
node {
sourceUrl
}
}
}
}
}
}
`
const page = parseInt(route.query.page) || 1
const postsPerPage = 5
const offset = (page - 1) * postsPerPage
const variables = {
first: postsPerPage,
after: null,
offset,
}
const { data } = await app.apolloProvider.defaultClient.query({ query, variables })
return {
posts: data.posts.edges.map(edge => edge.node),
pageInfo: data.posts.pageInfo,
currentPage: page,
totalPosts: data.posts.pageInfo.offsetPagination.total,
}
},
computed: {
totalPages() {
return Math.ceil(this.totalPosts / 10);
}
},
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment