【问题标题】:Vue - reload module on router pushVue - 在路由器推送上重新加载模块
【发布时间】:2020-08-27 21:04:31
【问题描述】:

我每个人。我对 Vue.js 很陌生。 所以我有这个 api 模块

axios.create({
  baseURL: URL,
  headers: {
    Authorization: 'Bearer ${localStorage.getItem('token')}'
  }
})

当我在登录页面并且没有设置令牌时(localStorage.getItem('token') 返回 null),模块已经加载,因为它用于登录请求。登录成功后,我执行localStorage.setItem('token', token) 但不幸的是,api 模块不会更新其令牌,直到我从浏览器手动刷新页面(我猜它不会自行刷新,因为它是单页应用程序)结束在我的 api 请求中有空令牌,直到我刷新。

你会如何解决这个问题?

起初我认为“这是一个登录,如果我重新加载页面就可以了”,所以我从this.$router.push('/') 切换到this.$router.go('/'),但是到索引的导航被破坏了。

我们将不胜感激任何类型的解决方案。

谢谢。

【问题讨论】:

  • 检查global default选项,你可以设置全局标题以及添加到localStorage。

标签: javascript vue.js


【解决方案1】:

我建议将您的 API 服务包装在 plugin 中,并使用它来管理您的 axios 实例。实现可能如下所示。

你想在你的 axios 实例中设置set the token explicitly

ApiService.js

const axios = require('axios');

// Function to create an axios instance.
const axiosFactory = (options) => axios.create({
    ...options,
    headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
    }
});

// To set the token in axios and save it in localStorage
const setTokenFactory = (axios) => (token) => {
    localStorage.item('token', token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}

// Vue plugin to set $api to axios and expose a setToken function in Vue.
const install = (Vue, axios) => {
    Vue.mixin({
        setToken: (token) => {
            setTokenFactory(Vue.protoype.$api)(token);
        }
    });
    Vue.prototype.$api = axios;
}

// Create an axios instance
const api = axiosFactory({
    baseURL: /* URL */
});
const setToken = setTokenFactory(api);
module.exports = {
    api,
    setToken,
    plugin: {
        install
    }
};

在你的main.js

const ApiService = require('./ApiService');
Vue.use(ApiService.plugin, ApiService.api);

要在 Vue 之外使用 api,您可以像这样使用它:

const { api, setToken } = require('./ApiService');

api.get();
setToken(token);

在 Vue 中,您可以使用 this.$api 来使用 axios。 要在用户登录时设置令牌,请使用 setToken 函数使用 this.setToken(token)

【讨论】:

  • 看起来不错,我会尝试,但我还需要在其他模块(组件之外)中调用该 $api。原因是我使用你给我的默认配置,然后我为我需要调用的每个端点重新定义一个新模块。那时我将我的端点请求模块导入到我需要从中调用导入端点的组件中。
  • 不幸的是 $api 在这些模块中似乎不可用。有什么建议吗?
  • 是的,这仅在您只想将 axios 与 vue 一起使用时才有效。除此之外,我会说将 axios 包装在不同的函数中。我将编辑一个示例的答案。
【解决方案2】:

登录后也可以自行设置token, 登录后获取令牌作为响应并设置它,或者从其他请求中询问令牌。

【讨论】:

  • 这就是我已经做的,但问题是 api 模块中令牌的值没有更新。
  • 您是否通过开发者控制台尝试过,尝试设置并获取值,看看会发生什么。
  • 我在 axios.create 上方使用localStorage.getItem('token') 添加了一个控制台日志,它仅在页面首次加载(登陆登录页面)时记录一次。由于它是一个单页应用程序,模块保持不变,在我刷新页面之前不会再次输出任何日志。
  • 在网络选项卡中我也可以看到我的 api 请求是用Authorization: Bearer null 发出的,这证实了这一事实。
  • 编辑您的问题并在您设置令牌的位置添加代码。
猜你喜欢
  • 2019-08-26
  • 2020-02-16
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2021-06-16
相关资源
最近更新 更多