【问题标题】:How to use GraphQL queries while using nuxt-apollo?使用 nuxt-apollo 时如何使用 GraphQL 查询?
【发布时间】:2021-04-19 01:30:12
【问题描述】:

我正在尝试从Django 端点查询数据,该端点使用Graphene Django 列出了我的所有articles。我遵循了所有文档,但无法理解如何在 vuex 操作中获取数据。

当使用GraphiQl 时,我可以获得数据答案。我已经安排了我的nuxt.config.js

apollo: {
    tokenName: "nuxt-apollo", // specify token name
    cookieAttributes: {
      expires: 7 // optional, default: 7 (days)
    },
    defaultOptions: {
      $query: {
        fetchPolicy: "network-only",
        errorPolicy: "all"
      }
    },
    watchLoading: "@/apollo/loadingHandler.js",
    errorHandler: "@/apollo/errorHandler.js",
    clientConfigs: {
      default: {
        httpEndpoint: 'http://localhost:8000/api/articles/graphql/'
      }
    }
  },

现在在我的vuex store,但我不知道如何查询和使用数据,我尝试如下查询但没有成功:

async fetchArticles({ commit }) {
    try {
      const response =  this.$axios.$get(
        'articles/graphql/',
        {
          query: query({
            query: gql`
              query Articles {
                allArticles {
                  id
                  title
                }
              }
            ` 
          }) 
        }
      )
        
    } catch (error) {
      commit('setError', error)
    }
  },

你能帮我解决我的问题吗? 谢谢

【问题讨论】:

    标签: axios graphql nuxt.js apollo


    【解决方案1】:

    您可以简单地安装 graphql-tag 库来创建通过 Apollo 客户端发送的查询。

    您也可以创建名为 article.graphql 的文件:

    query Articles {
        allArticles {
          id
          title
        }
     }
    

    也像这样传递参数来查询:

    query ($param: [String]) {
       //your query
    }
    

    以及店内使用情况:

    import articleQuery from './queries/article.graphql';
    ....
    // some store action
    async fetchArticles({ commit }) {
        const client = this.app.apolloProvider.clients.default;
    
        // Optional Param   
        // const param = format(new Date(), 'yyyy-MM-dd');
    
        const queryResult = 
           await client.query({
              query: articleQuery,
              // Optional (if query contain parameter you can use)
              // variables: { param }
            });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2023-03-15
      • 2021-01-01
      • 2018-06-09
      • 2020-04-22
      • 2020-04-26
      • 2020-02-05
      • 2018-10-07
      相关资源
      最近更新 更多