vue路由拦截,针对要先登录才能进入的页面
直接上代码:
router.js
{
path: '/Register',
name: 'Register',
component: (resolve) => {
require(['../components/Register'], resolve)
}
}, {
path: '/Luck',
name: 'Luck',
// 需要登录才能进入的页面可以增加一个meta属性
meta: {
requireAuth:true; //说明这个路由需要登录才能跳转
},
component: (resolve) => {
require(['../components/luck28/Luck'], resolve)
}
}
router.beforeEach((to,from,next)=>{
if(to.meta.requireAuth) {
//判断该路由是否需要登录权限
if(store.state.token) {
//通过vuex state获取当前的token是否存在
next();
}else{
next({ path:'/login', query:{redirect:to.fullPath}
//将跳转的路由path作为参数,登录成功后跳转到该路由})
} }else{
next(); }})
上面是简单的前端路由拦截器,但是有时候token时间长了会失效,则需要跳转页面时监听http请求
import axios from 'axios'
import store from './store/store'
import *astypes from './store/types'
import router from'./router'
//axios 配置
axios.defaults.timeout=5000;
axios.defaults.baseURL='https://api.github.com';
在main.js里面引用