vue中简单的导航守卫配置

1、需要在router.js中每个需要登录之后才有查看权限的页面中加入 meta: {requireAuth: true} ;
以下内容为router.js中内容;
export default [
{
path: ‘/login’,
name: ‘login’,
title: ‘登录’,
component: () => import(’@/components/login’),

},
{
path: ‘/’,
name: ‘home’,
title: ‘首页’,
component: () => import(’@/pages/home’),

},
{
path: ‘/contributeLists’,
name: ‘contributeLists’,
title: ‘贡献榜’,
component: () => import(’@/pages/contributeLists’),
meta: {requireAuth: true} // 需要登录才能查看的页面;
},
}
2、在router index.js中做如下处理;
import Vue from ‘vue’;
import Router from ‘vue-router’;
import routers from ‘./routers’; // 引入router.js
Vue.use(Router)

const router = new Router({
routes: routers, // 这里的键名一定要是routes
mode: ‘hash’
});
let uerId = cacheHelper.getCookie(‘userId’); // 用户id
// 实际此处应该为由后台提供的token,如果后台没能提供有效的token,只能退而求其次,使用用户id;
// cacheHelper 为自己处理本地缓存,localStorage,Cookie,sessionStorage二次封装的方法;
// let token= cacheHelper.getCookie(‘token’); // 用户id
router.beforeEach((to, from, next) => {
// 只需要判断requireAuth,是否为true即可;
if (to.matched.some(r => r.meta.requireAuth)) {
// 判断当前页面是否需要登录
if (!uerId) { // 用户id无效
// 判断用户id是否存在,实际应该判断token是否超时有效;
next({
path:’/login’
})

}else {
  next();
}

} else {
next();
}
})
3、第二种方法就是根据路由名字判断是否为自己想要跳转的路径,记得一定要加next();否则不会继续跳转
// router.beforeEach((to, from, next) => {
// // 登录设置token
// // const token = cacheHelper.getCookie(‘token’);
// // const tpken22 = this.Cookie.get(‘token’)
// // console.log(token);
// console.log(‘tpken22’);
// // console.log(tpken22);
// // if (to.name === ‘register’ || to.name === ‘password’) {
// // next()
// // } else {
// // if (!token && to.name !== ‘LOGIN_PAGE_NAME’) {
// // // 未登录且要跳转到页面不是登录页面
// // next({
// // name: ‘LOGIN_PAGE_NAME’
// // })
// // } else if (!token && to.name === ‘LOGIN_PAGE_NAME’) {
// // // 未登录 且要跳转的页面是登录页;
// // next()
// // } else if (token && to.name === ‘LOGIN_PAGE_NAME’) {
// // // 已经登录,且要跳转的页面是登录页
// // // next({
// // // name: ‘home’ // 跳转到home页首页
// // // })
// // next()
// // } else {
// // next();
// // }
// // }
// next();
// })

export default router;

发布了21 篇原创文章 · 获赞 0 · 访问量 2859

猜你喜欢

转载自blog.csdn.net/weixin_39593730/article/details/98382540