【问题标题】:How to use Vue2 plugins on Vue3 Composition API?如何在 Vue3 Composition API 上使用 Vue2 插件?
【发布时间】:2021-03-16 13:59:13
【问题描述】:

我正在迁移我的 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 上正常使用这些插件。

【问题讨论】:

  • 一种方法是从“vue”导入 Vue,然后使用 Vue.session(不带美元符号)。

标签: javascript vue.js vuejs3 vue-composition-api


【解决方案1】:

使用provide & inject

提供

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
}

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2021-11-30
    • 2022-06-29
    • 2022-01-23
    • 2022-08-06
    • 2021-11-15
    • 2021-12-24
    • 2022-08-19
    • 2020-12-19
    相关资源
    最近更新 更多