vue.js - 如何在 vue 组件之外访问“$apollo”?
问题描述
如何使 apollo 在 vue 组件之外访问。
我正在验证用户是否存在,然后允许路由继续进行。
{
path: '/:username',
name: 'userProfilePage',
component: userProfilePage,
beforeEnter(routeTo, routeFrom, next) {
userExist(routeTo.params.username)
next()
}
username
将作为参数传递给userExist
函数。
import gql from "graphql-tag"
export default function userExist(username) {
this.$apollo
.query({
query: gql`
query($username: String!) {
login(username: $username) {
username
email
}
}
`,
variables: {
username: username
}
})
.then(res => {
console.log(res);
return res
})
.catch(err => {
console.log(err);
return err
});
}
但它正在输出错误:
阿波罗客户端代码
import Vue from 'vue'
import App from './App.vue'
import VueApollo from 'vue-apollo';
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import router from './routes.js'
Vue.config.productionTip = false
const httpLink = new HttpLink({
uri: process.env.VUE_APP_DB_URL,
})
const cache = new InMemoryCache()
const apolloClient = new ApolloClient({
link: httpLink,
cache
})
Vue.use(VueApollo)
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
new Vue({
render: h => h(App),
router,
apolloProvider
}).$mount('#app')
解决方案
所以不要在 App.vue 文件中初始化 apollo 客户端,而是在另一个文件中初始化它。类似clients.js的东西,然后导出那个客户端:
const httpLink = new HttpLink({
uri: process.env.VUE_APP_DB_URL,
})
const cache = new InMemoryCache()
export const apolloClient = new ApolloClient({
link: httpLink,
cache
})
完成后,将其导入 App.vue 文件,如下所示:
import { apolloClient } from './clients.js';
Vue.use(VueApollo)
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
new Vue({
render: h => h(App),
router,
apolloProvider
}).$mount('#app')
完成后,将该客户端导入您想要的任何其他文件中:
import { apolloClient } from './client.js';
import gql from "graphql-tag"
export default function userExist(username) {
apolloClient
.query({
query: gql`
query($username: String!) {
login(username: $username) {
username
email
}
}
`,
variables: {
username: username
}
})
.then(res => {
console.log(res);
return res
})
.catch(err => {
console.log(err);
return err
});
}
推荐阅读
- react-native - React-native:iOS 应用程序在具有命名空间 SPRINGBOARD 的设备上的启动屏幕中崩溃
- angular - 如何根据这张图片对齐文字?
- javascript - 如何在带有按钮的测验应用程序中增加问题索引
- angular - 仅运行一次 Angular 更改检测并停止检测该组件的更改
- python - 如何在 django 中对秒外键执行计数?
- android - 应用程序关闭后我无法保持广播接收器运行
- jquery - 如何根据显示的内容更新导航项列表
- docker - 在 docker (2.2.7) 上找不到最新的 dotnet 核心映像
- r - 如何让分位数与 summarise_at 和 group_by (dplyr) 一起使用
- powershell - 我想删除特定文件名但保留特定文件名