Vue-路由器推送

时间:2020-08-27 08:15:23

标签: javascript vue.js

我每个人。我对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('/'),但是到索引的导航中断了。

任何形式的解决方案将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我建议将您的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)函数