如何使用 nuxt 和 @vue/composition-api provide/inject 进入 Vue root 实例?

How to provide/inject into Vue root instance WITH nuxt and @vue/composition-api?

我正在尝试将 @vue/apollo-composable 与我的 Nuxt-Ts 应用程序一起使用。这是如何将它注入到“普通”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 一个 $ 得到连接。如果我直接在 via ctx.app._provided = 中写一个 _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

我不使用 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'
  ],

只需设置一个 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 不太熟悉,但我认为代码应该可以正常工作。

nuxt-composition-api

中现在有一个官方的 onGlobalSetup 帮助程序

根据文档,您只需像这样在插件中使用它:

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

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