如何在Vue组件之外访问'$ apollo'?

时间:2019-02-25 08:13:50

标签: vue.js vue-apollo

如何在vue组件之外访问apollo。

我正在验证用户是否存在,然后允许路由继续进行。

{
        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
        });
}

但是它正在输出错误:

enter image description here

Apollo客户代码

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')

1 个答案:

答案 0 :(得分:1)

因此,与其在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
    });
}