Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access vue instance in Vuex

I declare a global variable in the main.js of the Vue.js project.

Vue.prototype.$API = "myapihere"

And I want to use this from everywhere. and it's work properly by using this.$API.

But in Vuex it does not work.

console.log(this.$API);

Here this.$API is undefined.

How I use my $API in Vuex.

like image 485
Rohit Nishad Avatar asked Mar 02 '20 15:03

Rohit Nishad


People also ask

Does Vue 3 Use Vuex?

The short answer is: Yes. Vuex is the preferred state management solution for Vue apps, and Vuex 4 is the version compatible with Vue 3. Do take note, however, that using Vuex for state management depends on the complexity of your application.

What is $store in Vue?

A "store" is basically a container that holds your application state. There are two things that make a Vuex store different from a plain global object: Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes.


1 Answers

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);
    }
  }
});
like image 156
Pierre Said Avatar answered Oct 11 '22 08:10

Pierre Said