How to get an vue-apollo instance with @vue/composition-api and nuxt.js

◇◆丶佛笑我妖孽 提交于 2019-12-25 01:31:44

问题


How do I configure vue-apollo,combined with @vue/apollo-composablefor consummation with @vue/composition-api orVue3.0?

Because although I get an default apolloClient via using @nuxtjs/apollo:

import { DefaultApolloClient } from "@vue/apollo-composable";
const myPlugin: Plugin = (context, inject) => {
  const defaultClient = ctx.app.apolloProvider.defaultClient;
   // do stuff with defaultClient, e.g. provide()
}

export default myPlugin

it's still empty instead of populated with my settings from nuxt.config.ts.

How can I create an working vue-apollo client using @vue/apollo-composable or how to create context.root.$apollo in the first hand?


回答1:


Here is my current approach for setting up vue-apollo in nuxt. This will most likely be a moving target as both of these packages are relatively new and in active development.

Package versions are

"@vue/apollo-composable": "4.0.0-alpha.1"
"@vue/composition-api": "version": "0.3.4"

Apollo Setup

//apolloClient.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import link from './link';

export default function apolloClient(_, inject) {
  const cache = new InMemoryCache();

  const client = new ApolloClient({
    // Provide required constructor fields
    cache,
    link,
    // Provide some optional constructor fields
    name: 'apollo-client',
    queryDeduplication: false,
    defaultOptions: {
      watchQuery: {
        fetchPolicy: 'cache-and-network',
      },
    },
  });

  inject('apollo', client);
}

// link.js
import { split } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import fetch from 'unfetch';
const httpLink = new HttpLink({
  uri: 'http://localhost:8080/v1/graphql',
  credentials: 'same-origin',
  fetch,
});

const wsParams = {
  uri: `ws://localhost:8080/v1/graphql`,
  reconnect: true,
};

if (process.server) {
  wsParams.webSocketImpl = require('ws');
}

const wsLink = new WebSocketLink(wsParams);

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);

export default link;

Then with the above, you include apollo in your nuxtconfig as a plugin

  plugins: [
    '~/plugins/vue-composition-api',
    '~/plugins/apolloClient'
  ],


来源:https://stackoverflow.com/questions/59362168/how-to-get-an-vue-apollo-instance-with-vue-composition-api-and-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!