vue.js - 如何在 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
}
}
}
`,
},
},
};
但是$apolloData
Vue 组件中的 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 在我的情况下是否真的不可用。
有什么提示吗?
谢谢!!
解决方案
我和你做的一样,我可以这样做:在 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
})
}
};
推荐阅读
- java - 如何在 switch 语句中执行 actionPerformed?
- python - 对象检测 API:置信度分数随着训练步骤数的增加而降低
- java - 从 crontab 调用 shell 脚本,但未执行脚本中的结束任务,但手动工作
- bash - 从文件名中提取日期子字符串
- sql - 为什么默认隔离级别为 READ COMMITTED 时 SQL Server 会读取未提交的数据?
- python - 如何使用 Python 以人类可读的方式打印纸牌
- linked-list - 试图在双向链表 ocaml 前面添加一个元素
- r - 唯一 ID 的 NA 值
- swift - 如何在文件夹中快速获取所有文件的完整路径
- python - 如何从 POST 请求中获取 auth 参数?