Fantasmic
Fantasmic

Reputation: 1202

How to use Vue2 plugins on Vue3 Composition API?

I am migrating my Vue2 App to use @vue/composition-api (Vue version still 2 not 3).

In Vue2 I use my plugins like this.$session however this won't work on Vue3. The solution I found was to use like this:

setup (props, context) {
  context.root.$session // works fine
  context.root.$anotherPlugin 
}

However in Vue3 context.root is @deprecated so when I migrate to Vue3 it will not work anymore.

Is there any other way to access Vue instance inside setup()? I think if I could access it I can use those plugins normally on Vue3.

Upvotes: 7

Views: 4221

Answers (1)

Dan
Dan

Reputation: 63059

Use provide & inject

Provide

const app = createApp(App);
app.provide('someVarName', someVar);  // Providing to all components here

Inject:

const { inject } = Vue;
...
setup() {
  const someVar = inject('someVarName');   // injecting in a component that wants it
}

Upvotes: 2

Related Questions