代码之家  ›  专栏  ›  技术社区  ›  igolka97

如何将计算数据添加到Vue Apollo的API响应中

  •  1
  • igolka97  · 技术社区  · 5 年前

    我有一个带有时间表和相应组件的页面。
    以下是我的单文件组件结构:

    ├─ ScheduleList
    ├─── ScheduleItem
    └────── SubSchedule
    

    我从API获得了一系列包含$apollo:smth的时间表,如下所示:

    export default {
      ...
      apollo: {
        scheduleItems: {
          query: ALL_SCHEDULE_ITEMS
           ...
    }  
    

    时间表的数据模型看起来像

    ScheduleItem {
      id: Int
      orderNumber: Int
      subSchedules: SubSchedule[]
      ...
    }
    
    SubScheduleItem {
        id: Int
        orderNumberInSchedule: Int
        schedule_id: Int // parent id
        duration: Int // in seconds
        ...
    }
    

    我想添加一个计算属性 start_time 阿波罗对每个目标的反应 subSchedule 对应 schedule 换句话说,我想在前端应用程序的API层上添加一个计算属性。

    使用计算道具的预期响应:

    [
      {
        id: 1,
        orderNumber: 1,
        subSchedules: [ { ..., duration: 100, ... } ],
        start_time: 0
      },
      {
        id: 2,
        orderNumber: 2,
        subSchedules: [ { ..., duration: 200, ... } ],
        start_time: 100
      }
    ]
    

    现在让我们从时间格式中抽象出来,想象一下:

    • 第一次的开始时间 子时间表 0 .
    • 时间总是以秒为单位,其中 0 是一天/事件/等的第一秒。

    我怎样才能让它工作?

    我以前在Vuex ORM中使用计算getter时使用过REST API,但apollo建议避免使用Vuex,因为apollo是应用程序状态管理的替代品。

    我正在使用Vue 2和JavaScript。

    0 回复  |  直到 5 年前