Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Vuex store in helper functions?

For vue-axios auth by api_token i use helper file api.js.

i got error - Uncaught TypeError: Cannot read property 'getters' of undefined.

I think api.js helper does not see global storage - Vuex $store.

In other components i do not need import Vuex storage, he avalaible in any place of app.

How use this.$storage in helper?

//api.js 
import axios from 'axios'

let api_token = this.$store.getters.get_api_token  //got error!


export function get(url) {
    return axios({
        method: 'GET',
        url: url,
        headers: {
            'Authorization': `Bearer ${api_token}`
        }
    })
}

//Vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        api_token: 'vnbnvnvnvb',

    },
    getters: {
        get_api_token(state){
            return state.api_token
        }
    },
});

export default store


//App.vue
import {get} from './helpers/api';
export default {

    created() {
        get(`/api/user/${1}`)
            .then((res) => {
                ///do it
            })
            .catch((err) => {
                console.log(err);
            })

    }
}
like image 787
Ilya Vo Avatar asked Jul 02 '17 10:07

Ilya Vo


People also ask

How do I get the Vuex store in JavaScript?

To get Vuex state from a JavaScript file with Vue. js, we can import the Vuex store and use it directly. to import the store from a module. Then we get a state value from the store with store.

Where is Vuex stored?

At the center of every Vuex application is the store. 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.


1 Answers

Found answer

// some JS file
import store from './../store'; // path to your Vuex store

let user = store.getters.user;
// do stuff with user

https://laracasts.com/discuss/channels/vue/vuex-accessing-vuex-outside-of-a-vue-component

like image 60
Ilya Vo Avatar answered Nov 09 '22 23:11

Ilya Vo