在 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粉5390555262024-01-22 11:32:17
// 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粉0116843262024-01-22 11:16:44
经过一天的搜索,我能够从 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, })
希望这可以帮助别人。如果有其他/更好的方法,请告诉我。谢谢