Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
nuxt store in external js file

I decided to rewrite my application from spa vue to nuxt but i faced a problem in spa, in vue i could just import store and used it but in nuxt i cant do the same, i am getting undefined object every time

in vue spa i had folder with some api services and with main api.js which include this code

import axios from 'axios'
import store from '@/store/index'

export default () => {
    return axios.create({
        baseURL: `http://myip.com/`,
        headers: {
            Authorization: `Bearer ${store.state.token}`
        }
    })
}

then in other js files i just import this api.js file and use something like this

import Api from '@/services/Api'

export default {
    register (credetinals){
        return Api().post('register', credetinals)
    },
    login (credetinals){
        return Api().post('login', credetinals)
    }
}

so i had 10 js files services where i include api.js and then in files *.vue i just import this service how can i do the same in nuxt ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you add your state under the /store/index.js it will automatically append in the application, you dont need to import it in your file.

What you can do is try to check the state using:

window.$nuxt.$store.state

Also dont forget to add a condition process.browser since you want to check it in browser.

Here is what I did in my api.js file for your reference:

// Libraries
import axios from 'axios';

// API Instance
export const instance = axios.create({
    baseURL: 'http://myip.com/',
    headers: {},
    validateStatus: status => {
        return status;
    },
});

// API Interceptors
instance.interceptors.request.use(config => {
    if (process.browser) {
        const userToken = window.$nuxt.$store.getters.getUserToken;
        // Set Authorization token
        if (userToken) {
            config.headers['Authorization'] = `Bearer ${userToken}`;
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda