[Vuejs]-Using Vuex State in main js

2👍

You’re asking how to access a Vuex store outside a Vue component. The syntax that you’re currently using is only valid if you’re writing a Vue component.

In case you want to access Vuex outside (any .js file) you should, first, export the store. Then, import that store in your file and finally use the store as you place.

Let’s see an example:

store/index.js

export const store = new Vuex.Store({
 state () {
  myBrachId: 'niceBranch007'
 }
});

Then, in any other .js file (main.js in your case)

import { store } from 'store/index.js'
console.log(store.state.myBrachId)

1👍

If you’re trying to add headers to axios I’d ask you to consider if you should really be getting that header data from a Vuex store anyways. Remember that any browser refresh will clear your store so you should not rely on it’s availability more than you need to. Using localStorage or sessionStorage might be better for what you’re looking to do here.

0👍

I am doing this right now this is my store

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {

    branchId: "",
  },
  getters:{
  
  },
  mutations: {
    
  },
  actions: {},
  modules: {}
});

In header cmponent

this.$store.state.branchId = this.Branches[index].branchId;

in main js

import Axios from 'axios'
import { store } from './store/index'
Axios.defaults.headers.common['BranchId'] = store.state.branchId;

this is not setting axios header, it comes empty

Leave a comment