首页 > 解决方案 > 如何在 Vuepress 站点中使用 vue-apollo?

问题描述

在一个 Vuepress 博客站点中,我在我的 markdown 博客文章中插入了一个组件,该组件从数据库获取信息以填充其数据。

我有一个 GraphQL 服务器来提供数据,所以我尝试使用vue-apollo在我的组件中获取它。

我尝试在enhanceApp.js文件中添加 vue-apollo,如下所示:

// enhanceApp.js
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import VueApollo from 'vue-apollo';

// HTTP connexion to the API
const httpLink = new HttpLink({
  // You should use an absolute URL here
  uri: 'http://localhost:3000/graphql',
});

// Cache implementation
const cache = new InMemoryCache();

// Create the apollo client
const apolloClient = new ApolloClient({
  link: httpLink,
  cache,
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
});

export default ({ Vue, options }) => {
  Vue.use(VueApollo);
  options = {
    ...options,
    apolloProvider,
  };
};

在我的组件文件中:

// component.vue

export default {
  apollo: {
    architects: {
      query: gql`{
          architects {
            nodes {
              name
            }
          }
        }
      `,
    },
  },
};

但是$apolloDataVue 组件中的 my 是空的,永远不会执行查询。

我认为它与Browser API Access Restrictions有关系,所以我尝试将查询放在mounted()钩子中:

// component.vue

export default {
  mounted() {
    this.$apollo
      .query({
        query: gql`{
          architects {
            nodes {
              name
            }
          }
        }
      `,
      })
      .then(result => {
        ...;
      })
}

这给我一个错误:

vue.runtime.esm.js?2b0e:619 [Vue 警告]:挂载钩子中的错误:“TypeError:无法读取未定义的属性‘defaultClient’”

这让我觉得里面的设置enhanceApp.js可能无法正常工作。

我看了一点ApolloSSR,但它似乎不适合我,因为我的 GraphQL 请求通常不依赖于路由。

我发现的一种解决方法是使用直接导入到我的组件文件中的 axios 或 ApolloClient:

// component.vue

<script>
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
const apolloClient = new ApolloClient({
  // You should use an absolute URL here
  uri: 'http://localhost:3000/graphql',
});

export default {
mounted() {
    apolloClient
      .query({
        query: gql`{
          architects {
            nodes {
              name
            }
          }
        }
      `,
      })
      .then(result => {
        ...;
      })
}

我想这可以工作,但我想知道 vue-apollo 在我的情况下是否真的不可用。

有什么提示吗?

谢谢!!

标签: vue.jsgraphqlapollovuepressvue-apollo

解决方案


我和你做的一样,我可以这样做:在 enhanceApp.js 中将 ApolloClient 更改为

import { ApolloClient } from 'apollo-boost';

现在在你的组件中使用这个:

export default {
   data() {
      return {
      allData:[],
    };
   },
apollo:{
  allData:{
    query: SUB_QUERY
  }
 },
methods: {
async geData (){
  const data = await this.$apollo.query(
        {query: SUB_QUERY},
        );
       }
      },
 mounted(){
   this.getData();
   apolloClient.query({
    query: SUB_QUERY
  })
 }
};

推荐阅读