简体   繁体   中英

Vue - reload module on router push

I everyone. I am quite new to Vue.js. So i have this api module

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

When i am in the login page and no token is set (localStorage.getItem('token') returns null) the module is already loaded since it is used for login request. When login is successful, i perform localStorage.setItem('token', token) but unfortunately the api module does not update its token until i manually refresh the page from the browser (i guess it doesn't refresh on its own since it is a single page application) ending up in my api requests to have null token until i refresh.

How would you solve this issue?

At first i thought "it's a login, it's ok if i make the page reload" so i switched from this.$router.push('/') to this.$router.go('/') but the navigation to the index gets broken.

Any solution of any kind will be much appreciated.

Thanks.

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

I'd recommend wrapping your API service in a plugin and using that to manage your axios instance. An implementation could look like this.

You want to set the token explicitly in your axios instance whenever you set it.

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

In your main.js

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

To use the api outside of Vue you can use it like:

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

api.get();
setToken(token);

And in Vue, you can use axios using this.$api . To set the token when user logs in, use the setToken function using this.setToken(token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM