使用 fetchMore
实现分页
这里 是服务器的一个简单示例。
有时您的数据集非常大,您希望逐块加载它。
使用智能查询上的 fetchMore()
方法加载更多数据。
警告
不要忘记在新的结果中包含 __typename
。
使用 variables()
时,不要更改返回的初始变量,否则列表数据将丢失。
示例
vue
<template>
<div id="app">
<h2>Pagination</h2>
<div class="tag-list" v-if="tagsPage">
<div class="tag-list-item" v-for="tag in tagsPage.tags">
{{ tag.id }} - {{ tag.label }} - {{ tag.type }}
</div>
<div class="actions">
<button v-if="showMoreEnabled" @click="showMore">Show more</button>
</div>
</div>
</div>
</template>
<script>
import gql from 'graphql-tag'
const pageSize = 10
export default {
name: 'app',
data: () => ({
page: 0,
showMoreEnabled: true,
}),
apollo: {
// Pages
tagsPage: {
// GraphQL Query
query: gql`query tagsPage ($page: Int!, $pageSize: Int!) {
tagsPage (page: $page, size: $pageSize) {
tags {
id
label
type
}
hasMore
}
}`,
// Initial variables
variables: {
page: 0,
pageSize,
},
},
},
methods: {
showMore () {
this.page++
// Fetch more data and transform the original result
this.$apollo.queries.tagsPage.fetchMore({
// New variables
variables: {
page: this.page,
pageSize,
},
// Transform the previous result with new data
updateQuery: (previousResult, { fetchMoreResult }) => {
const newTags = fetchMoreResult.tagsPage.tags
const hasMore = fetchMoreResult.tagsPage.hasMore
this.showMoreEnabled = hasMore
return {
tagsPage: {
__typename: previousResult.tagsPage.__typename,
// Merging the tag list
tags: [...previousResult.tagsPage.tags, ...newTags],
hasMore,
},
}
},
})
},
},
}
</script>