Search code examples
javascriptvue.jsvuex

Call state in another component Vue.js


I want to know how to call the contents of the updated state that are in another component?

I have an auth.js file:

state: {
  admin: [],
  token: '' // token default null
},
actions: { 
  async authIN({ commit }, admin) {
    try {
      ...
      commit('SET_TOKEN', response.data.token) // after submit
      ...
    } catch (err) {
      console.log(err);
    }
  }
},
mutations: {
  SET_TOKEN(state, newtoken) {
    state.token = newtoken;
    console.log("this-> new token ", state.token) // token already has its contents
  }
},
getters: {
  settokens: state => state.token
},

and in app.vue:

<v-app class="grey--text text--darken2" id="defaultFont">
  <v-main>
    <h2>ini , {{token}}</h2>
    <router-view />
  </v-main>
</v-app>

import { mapGetters } from "vuex";
export default {
  data: () => ({
    drawer: true,
    token:''
  }),
  components: {
    NavA,
    Loader,
    NavB,
  },
  mounted () {
    this.settokens()
  },
 computed: {
   ...mapGetters('Auth',['settokens'])
 },
};

How can I pass the contents of the state token in auth.js to app.vue? I am using Vuex version 2. can you help me?


Solution

  • In app.vue you can import your Vuex getters:

    import { mapGetters } from 'vuex';
    

    Then, in computed:

    computed: {
      ...mapGetters(['settokens'])
    }
    

    This way you can access it from anywhere in app.vue.