How to access vue instance in Vuex
I'm using Vue 3 and Vue.prototype.$foo
seems to have been removed for this version. I also found that in my version of VueX there is no this._vm
.
I explored the Provide / Inject method which is recommended by the Vue 3 docs. This worked nicely for accessing globals from within my components, but I couldn't access them from within store.
The solution I went for was to use globalProperties on the Vue object and standard properties on store
, and set them just before mounting 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 the globals in the same way in both store and components.
In a component:
export default {
data() {
return {
};
},
created() {
console.log( this.$conf.API_URL );
},
}
...and you can access this.$conf.API_URL
in the same way from actions, mutations and getters.
Once I'd found this solution I no longer needed access to the whole Vue instance from within store, but if you need it for some reason you can assign store.$app = app
; in the same place in main.js
.
You have 2 approaches:
Pass down the property (or even access the
_vm
property from inside Vuex) as an argument from a componentmethods: { this.$store.dispatch('someAction', this.$API) }
Declare and export that same variable from another file and consume it from your main.js AND your Vuex file:
// api.js export const API = "http://localhost:5000/api"
// main.js import { API } from './api.js ... Vue.prototype.$API = API
// store.js import { API } from './api.js // you can use API now!
Although I would personally lean towards the second, I would not store the API path in Vue at all as I'd rather have the api.js
file as a service to perform all ajax calls and consume that file from where I need.
use this._vm
here is why
by default when you access this
in vuex store
it will point store
so it will output something like this
so after that, you see that there is something called _vm
in store here it is
so that _vm
points to the vue component so to access it you will need to use this._vue
you can better create a getter of the vue instance like
const store = new Vuex.Store({
getters: {
vue(state) {
return this._vm
}
}
});
//so you can use it across your store
store.getters.vue
//Note
//the above way of accessing getter works on non `namespaced` stores
Vue 2 and Vuex 3 answer
In the store you can access the vue instance by accessing this._vm
const store = new Vuex.Store({
mutations: {
test(state) {
console.log(this._vm);
}
}
});