【问题标题】:nuxt store in external js filenuxt 存储在外部 js 文件中
【发布时间】:2021-11-19 19:00:47
【问题描述】:

我决定将我的应用程序从 spa vue 重写为 nuxt,但我在 spa 中遇到了一个问题,在 vue 中我可以导入 store 并使用它,但在 nuxt 中我不能这样做,我每次都得到未定义的对象

在 vue spa 中,我有一些 api 服务和包含此代码的主要 api.js 的文件夹

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

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

然后在其他 js 文件中,我只需导入这个 api.js 文件并使用类似的东西

import Api from '@/services/Api'

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

所以我有 10 个 js 文件服务,其中包含 api.js,然后在文件 *.vue 中我只导入此服务 我怎样才能在 nuxt 中做同样的事情?

【问题讨论】:

  • 你能控制台日志Api吗?

标签: javascript vue.js nuxt.js


【解决方案1】:

如果您在/store/index.js 下添加您的状态,它将自动附加到应用程序中,您无需将其导入文件中。

您可以尝试使用以下方法检查状态:

window.$nuxt.$store.state

另外不要忘记添加条件process.browser,因为您想在浏览器中查看它。

这是我在 api.js 文件中所做的供您参考:

// 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);
});

【讨论】:

  • 嗨,请不要发布代码图像,而是实际文本(带有突出显示)。
猜你喜欢
  • 2018-10-23
  • 2021-06-17
  • 2020-09-25
  • 2020-05-20
  • 1970-01-01
  • 2020-06-01
  • 2020-05-29
  • 2014-11-28
  • 1970-01-01
相关资源
最近更新 更多