In Vue2, I am able to access my Vue instance to use components registered in Vue.
test.js
import Vue from 'vue' export function renderLogin () { Vue.toasted.show('Please login again', { type: 'error', duration: 2000 }) }
In the above code, I am able to access the toasted package because I have registered it with Vue in main.js. However, in Vue3, I cannot use the toasted package because I cannot access the Vue instance inside the js file.
Need help on how to access the Vue instance ('this') inside the js file.
P粉5390555262024-01-22 11:32:17
// Vue 3 composition API
sssccc
This is not exactly the same way as in Vue2, but this might expose what you are looking for.
If you want a package to be globally available in Vue3, you may need to add the following code to the plugin:
//* 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);
This way you can get the toasted instance using the following command in the options api: this.$toasted
Use the composition API:
const { $toasted } = _instance.appContext.app.config.globalProperties;
In another plugin:
constructor(app) { app.config.globalProperties; }
P粉0116843262024-01-22 11:16:44
After a day of searching, I was able to access the toasted component from the vue instance inside the js file.
First we have to export the application instance to read it in js file
main.js
export const app = createApp({ render() { return h(AppWrapper); }, });
Next, we must register our component in the globalProperties of the application instance.
app.config.globalProperties.$toast = toast;
We can now import the application instance in the js file and access the toast component
test.js
import { app } from '@/main.js' app.config.globalProperties.$toast('Toast working fine', { type: 'success', duration: 2000, })
Hope this helps someone else. If there is any other/better way, please let me know. Thanks