Search code examples
vue.jsvuejs3

How do I access global property in composition setup API?


I'm brand new to Vue. The documentation says that the "setup" composition API is likely to be the one supported in the future so I'm trying to use that form everywhere.

I want to use a plugin, but I can't work out how to get access to it in the setup API format.

Here is the supplied example of how to do it in Composition API:

const authCode = await this.$gAuth.getAuthCode();

When I try to use the plugin in setup form of composition API then I get an error "Cannot read properties of undefined (reading '$gAuth') "

The LOC that is producing that error looks like this:

<script setup lang="ts">
... stuff ...
const googleUser = await this.$gAuth.signIn();

My main.ts looks like this:

import gAuthPlugin  from "vue3-google-oauth2";

app.use(gAuthPlugin , {
  clientId: "768834812579-ivi0oopbkqe05cg6t41p83t7gteekut6.apps.googleusercontent.com",
  scope: "email",
  prompt: "consent",
  fetch_basic_profile: false,
});

I can see that the plugin is defining a global property (here), which the Vue documentation says can be accessed on any component instance inside the application.

But the documentation only shows an example for composition (without setup) and I can't work out the syntax for this. It's quite similar to the problem raised in the comment to this downvoted answer (the actual answer didn't help me there).


Solution

  • You can't. Some packages like vue-router provide an alternative access method for the composition API, namely useRoute(), useRouter(). If the thing your using doesn't provide such, best option is probably to provide an injected value yourself in your app setup:

    const app = createApp(App);
    app.use(gAuthPlugin, { ... });
    app.provide('gAuth', app.config.globalProperties['$gAuth']);
    

    Usage:

    import { inject } from 'vue';
    const gAuth = inject('gAuth');