拦截器
1.拦截路由
// 拦截器// 路由拦截// to去哪个路由,from 从哪里来,next下一步router.beforeEach((to,from,next)=>{ // 如果是去login1 if (to.path == '/login1'){ //进行下一步 next(); } else{ //如果localStorage有值 if (localStorage.getItem('user_id')) { next() //否则回login1 }else{ next('/login1') } }})
最初的代码 我们进行优化 ,优化完
router.beforeEach((to, from, next) => { if (to.path == '/login1' || localStorage.getItem('user_id')) { next() } else { alert('请登录') next('/login1') }})优化完 看上去更精简
2拦截请求
axios.interceptors.request.use(function (hh) { if (!localStorage.getItem('user_id')){ router.path({ name:'/login1' }) } else{ hh.headers.user_id=localStorage.getItem('user_id')// 将localStorage.getItem('user_id') 发送到http的请求头里
} return hh},function (error) {})