首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用@vue/composition api和nuxt.js获取vue-apollo实例

如何使用@vue/composition api和nuxt.js获取vue-apollo实例
EN

Stack Overflow用户
提问于 2019-12-17 02:12:35
回答 1查看 1.2K关注 0票数 1

如何配置vue-apollo@vue/apollo-composable相结合,以完善@vue/composition-apiVue3.0

因为虽然我通过使用@nuxtjs/apollo获得了默认的apolloClient

代码语言:javascript
运行
复制
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

它仍然是空的,而不是填充我在nuxt.config.ts中的设置。

如何使用@vue/apollo-composable创建一个有效的vue-apollo client,或者如何直接创建context.root.$apollo

EN

Stack Overflow用户

回答已采纳

发布于 2019-12-17 03:39:34

这是我目前在nuxt中设置vue-apollo的方法。这很可能是一个移动的目标,因为这两个包都是相对较新的,并且正在积极开发中。

包版本为

代码语言:javascript
运行
复制
"@vue/apollo-composable": "4.0.0-alpha.1"
"@vue/composition-api": "version": "0.3.4"

Apollo设置

代码语言:javascript
运行
复制
//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;

然后,在上面的代码中,将apollo作为插件包含在nuxtconfig中

代码语言:javascript
运行
复制
  plugins: [
    '~/plugins/vue-composition-api',
    '~/plugins/apolloClient'
  ],
票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59362168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档