如何配置Vue Apollo Composable

时间:2020-10-10 18:51:10

标签: vue.js graphql vue-apollo vue-composition-api

我正在为graphql客户使用 vue add apollo 这是我的main.js配置文件。但是在此我不知道 apolloClient 的来源,我尝试从 vue-appolo.js 导入 apolloClient ,但是它不起作用,帮助如何配置此内容感谢您的帮助

    import VueCompositionApi, { provide } from "@vue/composition-api";
    import { DefaultApolloClient } from "@vue/apollo-composable"; 
    import { createProvider } from './vue-apollo'

    Vue.use(VueCompositionApi)
    new Vue({
      router,
      store,
      setup () {
        provide(DefaultApolloClient, apolloClient )
      },
      apolloProvider: createProvider(),
      i18n,
      render: h => h(App)
    }).$mount('#app')

和我的vue-apollo.js,但我不知道将 apolloClient 导入到 main.js


    import Vue from 'vue'
    import VueApollo from 'vue-apollo'
    import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'
    
    Vue.use(VueApollo)
    
    const AUTH_TOKEN = 'apollo-token'
    const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || 'http://localhost:3000/graphql'
    export const filesRoot = process.env.VUE_APP_FILES_ROOT || httpEndpoint.substr(0, httpEndpoint.indexOf('/graphql'))
    
    Vue.prototype.$filesRoot = filesRoot
    
    const defaultOptions = {
      httpEndpoint,
      wsEndpoint: null,
      tokenName: AUTH_TOKEN,
      persisting: false,
      websocketsOnly: false,
      ssr: false
    }
    
    export function createProvider (options = {}) {
      const { apolloClient, wsClient } = createApolloClient({
        ...defaultOptions,
        ...options
      })
      apolloClient.wsClient = wsClient
    
      const apolloProvider = new VueApollo({
        defaultClient: apolloClient,
        defaultOptions: {
          $query: {
          }
        },
        errorHandler (error) {
          console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
        }
      })
    
      return apolloProvider
    }
    
    export async function onLogin (apolloClient, token) {
      if (typeof localStorage !== 'undefined' && token) {
        localStorage.setItem(AUTH_TOKEN, token)
        localStorage.setItem('tokenDate', new Date())
      }
      if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
      try {
        await apolloClient.resetStore()
      } catch (e) {
        console.log('%cError on cache reset (login)', 'color: orange;', e.message)
      }
    }
    
    export async function onLogout (apolloClient) {
      if (typeof localStorage !== 'undefined') {
        localStorage.removeItem(AUTH_TOKEN)
      }
      if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
      try {
        await apolloClient.resetStore()
      } catch (e) {
        console.log('%cError on cache reset (logout)', 'color: orange;', e.message)
      }
    }

0 个答案:

没有答案