如何在 Vue.js 中使用联合片段?

How do I use fragments on union in Vue.js?

有谁知道如何在联合上使用片段?我看过 React (https://www.apollographql.com/docs/react/advanced/fragments/#fragments-on-unions-and-interfaces) 的文档,但 Vue 的文档不多。我有一个查询 returns 两个片段,都带有 __typename.

query {
    search(queryString: "lin") {
        ... on Professor {
            __typename
            name
        }
        ... on Course { 
            __typename
            name
            moduleCode
        }
    }
}

当 vue 应用程序运行时,我收到错误消息"You're using fragments in your queries, but either don't have the addTypename: true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename."这是我的 vue 应用程序的代码。

data() {
    return {
        result: []
    };
},
apollo: {
    // Query with parameters
    result: {
        // gql query
            query: gql'
                query search($queryString: String!) {
                    ... on Professor {
                        __typename
                        name
                    }
                    ... on Course { 
                        __typename
                        name
                        moduleCode
                    }
                }
            ',
            // Static parameters
            variables() {
               return {
                  queryString: 'lin mei'
                }
          }
    }
},
// In my apollo client options
// Override default cache
cache: new InMemoryCache(
    { addTypename: true }
}

我收到的错误信息是

有没有人能提供一个从 vue 中的查询中抓取两个片段的例子?

您的查询不正确。您已将您的操作命名为 search,但您可能打算改为在根类型上查询此字段。类似于:

query ($queryString: String!) {
  search(queryString: $queryString) {
    ... on Professor {
      __typename
      name
    }
    ... on Course { 
      __typename
      name
      moduleCode
    }
  }
}

注意:因为我不知道您的架构,所以我也不能肯定上面的查询是有效的。如果您查询的服务器公开了 GraphiQL 或 GraphQL Playground 接口,您应该使用它来验证您的查询,因为这两种工具都使用 schema-specific 语法突出显示。

您可能希望向每个片段添加一个 id_id 字段以确保正确的缓存行为。如果两个字段都不存在,您将需要提供自定义 dataIdFromObject 函数。有关更多详细信息,请参阅 the docs