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

Fan*_*mic 7 javascript vue.js vuejs3 vue-composition-api

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

在 Vue2 中我使用我的插件,this.$sessionthis在 Vue3 上不起作用。我找到的解决方案是这样使用:

setup (props, context) {
  context.root.$session // works fine
  context.root.$anotherPlugin 
}
Run Code Online (Sandbox Code Playgroud)

然而在 Vue3 中context.root@deprecated这样,当我迁移到 Vue3 时它就不再工作了。

还有其他方法可以访问里面的Vue实例吗setup()?我想如果我可以访问它,我就可以在 Vue3 上正常使用这些插件。

Dan*_*Dan 3

使用provideinject

提供

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

注入

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