简体   繁体   中英

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.

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
}

The way I do it is to use getCurrentInstance which also exists in the vue 2 composition api.

You can use it like so:

const instance = getCurrentInstance()
const session = instance.proxy.$session
const i18n = instance.proxy.$i18n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM