'Access Vue instance in Nuxt plugin

i created a nuxt plugin to use the simple-jsonrpc-js package together with the nuxt auth plugin. Now i can access it with this.$jsonApi.call() to perform a request to the server with my token provided by nuxt/auth.

I use it in many components within my nuxt app so i wanted to create an error handler for my plugin by wrapping _jrpc.call() in a try-catch block. Because im using Vuetify i want to show a snackbar component with the content of the error Message. Currently my code looks like this:


async call<T = Response<any>>(method: string, data: object = {}): Promise<T> {
    const token = this.accessTokenFactory()
    try {
        return await this._jrpc.call(method, {
            token: token,
            data
        })
    } catch (e:any) {
        const ComponentClass = Vue.extend(VSnackbar)
        const instance = new ComponentClass()
        instance.$slots.default = [e.message]
        instance.$mount()
        document.querySelector('body')?.appendChild(instance.$el)
    }
}

But when i get an error from my api, i get this error from the catch block

enter image description here

Which comes from the vuetify component code:

const {
  bar,
  bottom,
  footer,
  insetFooter,
  left,
  right,
  top,
} = this.$vuetify.application

My guess is that the Vue instance i am using doesn't have the this.$vuetify.application becuase its not the same as the Vue instance used by the nuxt application...

That's why im asking: how do i access the same Vue instance in Nuxt when injecting a plugin? The Nuxt docs arent helping and i haven't found a similar question.

Thanks in advance for helping



Solution 1:[1]

Currently i haven't found a solution but an alternative in this article

How to create a global snackbar using Nuxt, Vuetify and Vuex.

IMHO this isn't as "clean" as a plugin since the listening component sits in /layouts/default rather than the nuxt/vue context and therefore needs to be added it in all layouts to work.

I guess a workaround would be a "base" layout from which the all other layouts need to inherit

Solution 2:[2]

Found the answer to this just now! I've been try to search for this for quite some time now as well.

You can access the root Vue instance used by Nuxt from the client as window.$nuxt (which is the same as this.$root inside the Vue components).

For your code, use window.$nuxt.$vuetify.application on the calling code.

NOTE: If you are using this on the plugin creation itself, make sure to wait for the Nuxt instance to be created first, by either doing a setTimeout, hooking through a module, or adding a component event, because the Nuxt instance has not been created yet.

EDIT: Fixed the sentence wording and added some insight.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 impaect
Solution 2