utils文件夹中新建js文件 loginAuto.js
export function setExpire(key, value, expire) {
let obj = {
data: value,
time: Date.now(),
expire: expire
};
localStorage.setItem(key, JSON.stringify(obj));
}
export function getExpire(key) {
let val = localStorage.getItem(key);
if (!val) {
return val;
} else {
val = JSON.parse(val);
if (Date.now() - val.time > val.expire) {
localStorage.removeItem(key);
return null;
}
return val.data;
}
}
request.js 文件中 设置请求拦截 赋值token
//请求拦截
if (getExpire('userToken')) {
config.headers.informationputuid = getExpire('userToken');
}
//响应拦截 配置token过期时间
setExpire('userToken', response.headers.informationputuid, 14 * 24 * 60 * 60 * 1000);
router.js 文件 路由拦截 有token无密码登录否则正常登录 **注意next() 重复调用会报错
router.beforeEach((to, from, next) => {
if (to.path === '/login' || to.path === '/') {
next();
} else {
if (to.meta.title) {
document.title = to.meta.title;
}
if (getExpire('userToken')) {
next();
} else {
console.log('pms out');
next('/login');
}
}
});