如何使用Apollo在Vue中实现有效的Graphql查询?

Cod*_*nKy 3 javascript apollo vue.js graphql vue-apollo

有人可以帮我使用scaphold.io进行第一个查询吗?

当我使用内部GraphiQL查询以下内容时:

query AllPrograms {
  viewer {
    allPrograms{
      edges {
        node {
          id
          name
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

回报看起来像这样:

{
  "data": {
    "viewer": {
      "allPrograms": {
        "edges": [
          {
            "node": {
              "id": "UHJvZ3JhbTo2",
              "name": "Blender"
            }
          },
          {
            "node": {
              "id": "UHJvZ3JhbTo1",
              "name": "Inkscape"
            }
          },

          ...
Run Code Online (Sandbox Code Playgroud)

我的组件看起来像这样:

<template>
  <md-card>
    <span class="md-headline">Programma's</span>
    <span class="md-headline">{{ allPrograms }}</span>
  </md-card>
</template>


<script>
import gql from 'graphql-tag'
import config from '../../config/client'

const log = console.log

const allPrograms = gql `
  query AllPrograms {
    viewer {
      allPrograms{
        edges {
          node {
            id
            name
          }
        }
      }
    }
  }
`

export default {
  props: [],
  data () {
    return {
      allPrograms: '',
    }
  },
  // Apollo GraphQL
  apollo: {
    // Local state 'posts' data will be updated
    // by the GraphQL query result
    allPrograms: { // <-- THIS allPrograms IS THE CAUSE OF THE ERROR!
      // GraphQL query
      query: allPrograms,
      // Will update the 'loading' attribute
      // +1 when a new query is loading
      // -1 when a query is completed
      loadingKey: 'loading',
    },
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:结果缺少所有程序属性

而且我还读了一些看起来像是正确的json结果的一部分的东西: object: viewer: {allPrograms: Object, __typename: "Viewer"}

也许我误会了一些东西。我想我已经很接近接收数据了,也许已经成功了,但是拆分似乎需要额外的注意。

有任何想法吗?

nik*_*shr 6

似乎vue-apollo希望data在服务器发送的响应中找到与您在阿波罗定义中设置的键匹配的键。尝试更换

apollo: {
   allPrograms: { ... }
} 
Run Code Online (Sandbox Code Playgroud)

通过

apollo: {
   viewer: { ... }
} 
Run Code Online (Sandbox Code Playgroud)

错误消失了,但这可能不是您想要的。

而是update在您的查询定义中添加一个选项来更改数据集。假设您想要的内容allPrograms

apollo: {
    allPrograms: {
        query: allPrograms,
        loadingKey: 'loading',
        update: function(data) {
            return data.viewer.allPrograms;

            // or if you just want the leaf objects
            return data.viewer.allPrograms.edges.map(function(edge) {
                return edge.node;
            });
        }
    },
}
Run Code Online (Sandbox Code Playgroud)