簡體   English   中英

如何在 Vue3 Composition API 上使用 Vue2 插件?

[英]How to use Vue2 plugins on Vue3 Composition API?

我正在遷移我的 Vue2 應用程序以使用@vue/composition-api (Vue 版本仍然是 2 而不是 3)。

在 Vue2 中,我使用像this.$session這樣的插件, this在 Vue3 上不起作用。 我找到的解決方案是這樣使用:

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

但是在 Vue3 中context.root@deprecated ,所以當我遷移到 Vue3 時,它將不再工作。

還有其他方法可以在setup()中訪問 Vue 實例嗎? 我想如果我可以訪問它,我可以在 Vue3 上正常使用這些插件。

使用provideinject

提供

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

注入

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

我這樣做的方法是使用也存在於 vue 2 組合 api 中的getCurrentInstance

你可以像這樣使用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM