I declared a global variable in main.js
of the Vue.js project.
Vue.prototype.$API = "myapihere"
I want to use it everywhere.
Using this.$API
works fine.
But in Vuex it doesn't work.
console.log(this.$API);
Here this.$API
is undefined.
How do I use my $API
in Vuex.
P粉1949190822023-10-23 13:35:05
I'm using Vue 3, and Vue.prototype.$foo
seems to have been removed in this version. I also discovered that this._vm
is not present in my version of VueX.
I explored the Provide/Inject method, which is provided by the Vue 3 documentation. This works great for accessing global variables from within my component, but I cannot access them from within the store.
The solution I'm looking for is to use the object and standard properties on Vue's globalProperties store
and set them before installing the app.
main.js
:
import store from './store/index'; import App from './App.vue'; // Load custom globals import conf from '@/inc/myapp.config'; const app = createApp(App) .use(store); // Register globals in app and store app.config.globalProperties.$conf = conf; store.$conf = conf; app.mount('#app');
What I like about this is that I can access global variables the same way in storage and components.
In component:
export default { data() { return { }; }, created() { console.log( this.$conf.API_URL ); }, }
...You can access this.$conf.API_URL
in the same way via operations, mutations and getters.
Once I found this solution I no longer needed to access the entire Vue instance from within the store, but if you need it for some reason you can assign store.$app = app
;In the same location in main.js
.
P粉0546168672023-10-23 11:53:45
Vue 2 and Vuex 3 Answers
You can access the vue instance in the store by accessing this._vm
const store = new Vuex.Store({ mutations: { test(state) { console.log(this._vm); } } });