如何通过nuxt和@ vue / composition-api提供/注入Vue根实例?

时间:2019-12-05 15:07:51

标签: typescript nuxt.js vue-apollo vuejs3 vue-composition-api

我正在我的Nuxt-Ts应用程序中尝试使用@vue/apollo-composable。这是示例应如何将其注入“正常” Vue应用程序的根实例中的方法:

import { provide } from '@vue/composition-api'
import { DefaultApolloClient } from '@vue/apollo-composable'

const app = new Vue({
  setup () {
    provide(DefaultApolloClient, apolloClient)
  },

  render: h => h(App),
})

问题:我不知道如何访问Nuxt-TS中的根实例

我尝试制作一个插件,但是它直接注入了根实例(这是不对的,因为@vue/apollo-composable使用的是composition-api::provide(),它创建了自己的属性_provided

如果我使用nuxt插件的inject$,则会串联在一起。而且,如果我通过_provided直接写一个ctx.app._provided =对象,它不会粘住。

import { DefaultApolloClient } from "@vue/apollo-composable";
const myPlugin: Plugin = (context, inject) => {
  const defaultClient = ctx.app.apolloProvider.defaultClient;
  inject(DefaultApolloClient.toString(), defaultClient) // results in $$ and also composition-api::inject is checking inside `_provided[DefaultApolloClient]`
}

export default myPlugin

我不能像原始示例中那样调用provide(),因为它只能在VueComponent::setup函数中使用。

我还尝试创建一个组件,并仅在需要它的页面上使用它(虽然有点违反了在根实例中安装的目的)

const InstallGraphQl = createComponent({
  name: "InstallGraphQl",
  setup(_props, ctx: any) {
    debugger;
    const apolloClient = ctx.app.apolloProvider.defaultClient;
    ctx.provide(DefaultApolloClient, apolloClient);
  },
});
export default createComponent({
  name: "DefaultLayout",
  components: {
    InstallGraphQl
  },
  setup(_props, _ctx: SetupContext) {
    const { result } = useQuery(SharedLayoutQuery);
    return { result };
  },
});

但是随后在setup ...

之前调用了导出的组件中的InstallGraphQl::setup

编辑:有关@vue/apollo-composable的更多信息,请参见此处的讨论:https://github.com/vuejs/vue-apollo/issues/687

3 个答案:

答案 0 :(得分:3)

只需将setup()设置为根选项:

/* plugins/provide-apollo-client.js */

import {provide} from '@vue/composition-api'
import {DefaultApolloClient} from '@vue/apollo-composable'

export default function ({app}) {
  app.setup = () => {
    provide(DefaultApolloClient, ...)
  }

  // Or, use local mixin
  app.mixins = (app.mixins || []).concat({
    setup () {...},
  })
}
/* nuxt.config.js */

export default {
  plugins: ['~/plugins/provide-apollo-client'],
}

虽然对nuxt-ts不太熟悉,但是我认为代码应该可以正常工作。

答案 1 :(得分:2)

我不使用nuxt-ts,但是在nuxt应用程序中确实有此设置。在我的default.vue模板中,我是这样提供的。

<script>
  import { provide } from '@vue/composition-api';
  import { ApolloClients } from '@vue/apollo-composable'

  export default {
    setup(props, context) {
      provide(ApolloClients, {
        default: context.root.$apollo,
      })
    }
  }
</script>

软件包版本为

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

Apollo设置

//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中

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

答案 2 :(得分:1)

nuxt-composition-api中现在有一个官方的onGlobalSetup助手

根据文档,您可以像这样在插件中简单地使用它:

import { onGlobalSetup } from 'nuxt-composition-api'

export default () => {
  onGlobalSetup(() => {
    provide('globalKey', true)
  })
}