如何在Vue3中访问js文件中的Vue实例?
P粉609866533
P粉609866533 2024-01-21 16:04:50
0
2
785

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

测试.js

import Vue from 'vue'

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

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

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

P粉609866533
P粉609866533

全部回复(2)
P粉539055526

// Vue 3 组合 API

    sssccc

这与 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);

这样,您就可以在选项 api 中使用以下命令获取 toasted 实例: this.$toasted

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

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

P粉011684326

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

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

main.js

export const app = createApp({
   render() {
     return h(AppWrapper);
   },
});

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

app.config.globalProperties.$toast = toast;

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

测试.js

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!