【问题标题】:Implementing laravel lighthouse pagination on the front-end在前端实现 laravel 灯塔分页
【发布时间】:2021-11-23 03:15:59
【问题描述】:

我正在尝试使用 nuxt 前端和 laravel 后端在我的网站上实现分页,该后端使用 lighthouse 为 graphql 端点提供服务。

阅读有关 pagination 指令的文档让我对它的工作原理提出了很多问题。

不同于正常的 laravel 分页方式,它在模型上调用 paginate(),然后返回具有以下项目的对象

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // Record...
        },
        {
            // Record...
        }
   ]
}

graphql(或至少是 lighthouse)做的有点不一样,主要是以下需要做的。

你定义一个查询

type Query {
    blogs: [Blog!]! @paginate  @orderBy(column: "created_at", direction: DESC)
}

使用以下参数first : 5, page:1 通过 graphql-playground 查询它会得到以下对象

{
  "data": {
    "blogs": {
      "paginatorInfo": {
        "count": 5,
        "currentPage": 1,
        "firstItem": 1,
        "hasMorePages": true,
        "lastItem": 5,
        "lastPage": 2,
        "perPage": 5,
        "total": 10
      },
      "data": [
        // items
      ]
    }
  },
}

看起来很简单,但我不完全确定如何在前端进行这项工作

我做了一个分页组件

<template>
  <div class='btn-group bg-white py-2 items-center justify-center'>
    <button class='btn'>Previous</button>
    <button class='btn'>1</button>
    <button class='btn btn-active'>2</button>
    <button class='btn'>3</button>
    <button class='btn'>4</button>
    <button class='btn'>Next</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination'
}
</script>

<style scoped>

</style>

这真的是我所知道的,我已经敲了几个小时的头来阅读阿波罗和分页,但到目前为止我看到的唯一例子是无限卷轴类型,而不是好的'oll基于偏移的分页。

【问题讨论】:

    标签: laravel nuxt.js laravel-lighthouse


    【解决方案1】:

    在您的客户端,您将拥有一个带有一些变量的 Graphql 查询。例如:

    query Blogs($page: Int!, $first: Int!) {
        blogs(page: $page, first: $first) {
          id
          # ...
        }
    }
    

    因此,对于 Apollo,您必须通过这些变量来调用它,例如:

    data() {
      return {
        page: 1,
      }
    },
    apollo: {
      blogs: {
        query: gql`...`,
        variables() {
          return {
              first: 15, // it could be dynamic
              page: this.page, // in your component, you will have to change this variable to fetch another page
          }
        }
      }
    }
    

    然后,每次更改 page 变量时,Apollo 都会进行另一个查询以获取其他页面。通常我使用预制组件进行分页,例如v-pagination

    【讨论】:

    • 嘿,我已经准备好查询,但我使用的是tailwind css,这意味着我必须构建自己的分页组件。也许我会换成 vuetify
    猜你喜欢
    • 2022-11-25
    • 2021-09-13
    • 2021-09-10
    • 2021-11-20
    • 2019-08-22
    • 2018-07-03
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多