【发布时间】:2019-08-02 14:12:16
【问题描述】:
在一个 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
}
}
}
`,
},
},
};
但是我在Vue组件中的$apolloData是空的,查询永远不会执行。
我认为它与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.js graphql apollo vuepress vue-apollo