10

In Vue2, I was able to access my Vue instance to make use of components registered with 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 as I have already registered it with Vue in my main.js. However, in Vue3 I'm unable to use the toasted package as I'm unable to access the Vue instance inside a js file.

Need help on how to access Vue instance('this') inside a js file.

1
  • please share the to the package repository Commented Aug 3, 2021 at 8:18

4 Answers 4

8

After a day of searching, I was able to access the toasted component from the vue instance inside a js file.

First, we would have to export the app instance to be able to read it in a js file

main.js

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

Next, we would have to register our component in our globalProperties of our app's instance.

app.config.globalProperties.$toast = toast;

We can now import the app instance in our js file and access toast component

test.js

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

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

Hope this helps someone out. Please let me know if there are other/better ways. Thank you

Sign up to request clarification or add additional context in comments.

2 Comments

This should work, but is not the most clean solution, because app.config indicates its purpose is for configuration settings, not for state, which can change during app runtime. It would be better to use the provide/inject mechanism.
Uncaught ReferenceError: Cannot access 'App' before initialization
4

// Vue 3 Composition API

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

It's not exactly the way as in Vue2, but this will probably expose what you are looking for.


If you want to make a package globally available in Vue3 you probably need to add the following code to a 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);

With this you are able to get the toasted instance in the options api with: this.$toasted

And with the composition api: const { $toasted } = _instance.appContext.app.config.globalProperties;

And in another plugin with: constructor(app) { app.config.globalProperties; }

3 Comments

Hey thanks for answering, but this concept woudn't work a js file right?? It works only on a Vue component. Please correct me if im wrong
can this work inside a js file? For example, how can I access a $log variable in a js file encapsulated the axios requests? The API refrence said that getCurrentInstance only works during setup or Lifecycle Hooks.
But he asked for JS file not for vue file
0

2023 Update

This works in Vue 3.3.4.

<script src="https://unpkg.com/[email protected]"></script>
<div id="app">{{ myValue }}</div>
<script>
const app = Vue.createApp({
  data: function () {
    return {
      myValue: 'a'
    };
  },
  methods: {
    setMyValue: function (value) {
      this.myValue = value;
    }
  }
});
app.mount('#app');

setTimeout(function () {
  app._instance.ctx.$data.myValue = 'b';
}, 1000);

setTimeout(function () {
  app._instance.ctx.setMyValue('c');
}, 2000)
</script>

1 Comment

Code-only answers should be updated to explain how the code resolves the question, further guidance can be found in the Help Center
-2

You can use provider/inject.

For example if you want to use axios across my components, provide axios in your main.js

import { createApp } from "vue";
import App from "./App.vue";
import axios from "axios";

const app = createApp(App);

app.provide("http", axios);

app.mount("#app");

Then in SFC component you could access by 2 ways:

// Composition API
<script>
import { inject } from 'vue'

export default {
  setup() {
    const http = inject("http");
    http.get("https://jsonplaceholder.typicode.com/todos/1").then((response) => {
      console.log(response.data);
    });
  }
}
</script>

// Vue 2 options API
<script>
export default {
  inject: ["http"],
}
</script>

Original answer here.

2 Comments

Please write a brief summary of the content of the link you provide (even if it is a SO answer). Remember that such content may no longer be available later, making this answer invalid.
As I mentioned, I need to access the Vue instance inside a js file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.