如何在Vue3中访问js文件中的Vue实例?

Jon*_*ton 10 javascript vue.js vuejs2 vuejs3

在 Vue2 中,我能够访问我的 Vue 实例以使用在 Vue 中注册的组件。

测试.js

   import Vue from 'vue'

   export function renderLogin () {
     Vue.toasted.show('Please login again', { type: 'error', duration: 2000 })
   }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我能够访问 toasted 包,因为我已经在 main.js 中使用 Vue 注册了它。但是,在 Vue3 中,我无法使用 toasted 包,因为我无法访问 js 文件内的 Vue 实例。

需要有关如何访问 js 文件中的 Vue 实例('this') 的帮助。

Jon*_*ton 8

经过一天的搜索,我能够从 js 文件内的 vue 实例访问 toasted 组件。

首先,我们必须导出应用程序实例才能在 js 文件中读取它

main.js

export const app = createApp({
   render() {
     return h(AppWrapper);
   },
});
Run Code Online (Sandbox Code Playgroud)

接下来,我们必须在应用程序实例的 globalProperties 中注册我们的组件。

app.config.globalProperties.$toast = toast;
Run Code Online (Sandbox Code Playgroud)

我们现在可以在 js 文件中导入应用程序实例并访问 toast 组件

测试.js

import { app } from '@/main.js'

app.config.globalProperties.$toast('Toast working fine', {
    type: 'success',
    duration: 2000,
  })
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助别人。如果有其他/更好的方法,请告诉我。谢谢


Ron*_*ldT 5

// Vue 3 组合 API

    <script>
      import { getCurrentInstance } from 'vue';
    
      export default {
        setup() {
          const _instance = getCurrentInstance();
          const vueInstance = _instance.appContext;
        },
      };
    </script>
Run Code Online (Sandbox Code Playgroud)

这与 Vue2 中的方式不完全一样,但这可能会暴露您正在寻找的内容。


如果你想让一个包在 Vue3 中全局可用,你可能需要将以下代码添加到插件中:

    //* This will help for accessing the toasted instance in other files (plugins)
    app.config.globalProperties.$toasted = toasted;

    //* This will expose the toasted instance in components with this.$toasted
    app.provide('$toasted', toasted);
Run Code Online (Sandbox Code Playgroud)

这样你就可以在 options api 中获取 toasted 实例:this.$toasted

并使用组合 api: const { $toasted } = _instance.appContext.app.config.globalProperties;

在另一个插件中: constructor(app) { app.config.globalProperties; }

  • 这可以在js文件中工作吗?例如,如何访问封装 axios 请求的 js 文件中的“$log”变量?[API 参考](https://v3.vuejs.org/api/composition-api.html#getcurrentinstance) 表示“getCurrentInstance”仅在设置或生命周期挂钩期间有效。 (3认同)