在router——>index.js文件中:先加入meta: {
requireAuth: true,
}:
{
path: '/',
name: 'Login',
component: Login,
meta: {
requireAuth: true,
}
},
再添加:
const VueRouter = new Router ({
routes,
});
VueRouter.beforeEach((to, from, next) => {
if (to.matched.some((r) => r.meta.requireAuth)) {
let user = JSON.parse(sessionStorage.getItem('user'));
if (user) { //判断是否已经登录
console.log('通过拦截',from);
next();
} else {
// this.$message({
// message: '请先登录!',
// type: 'warning'
// });
console.log('未通过拦截',from);
next({
path: '/',
query: {redirect: to.fullPath} //登录成功后重定向到当前页面
});
}
} else {
console.log('没有设置是否要拦截,直接拦截');
next();
}
//如果本地 存在 token 则 不允许直接跳转到 登录页面
if(to.fullPath === "/"){
if(sessionStorage.getItem('user')){
next({
path:from.fullPath
});
console.log('你已经登录,不能直接跳到登录页面',from);
}else {
console.log('你没有登录,可以直接跳到登录页面',from);
next();
}
}
});
export default VueRouter;
如果要对角色权限判断,添加role:
{
path: '/helloWorld',
name: 'HelloWorld',
component: HelloWorld,
meta: {
requireAuth: true,
role:['admin'] //指定admin角色能访问
}
},
再使用to.meta.role==user.role
判断
附上完整代码:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Test from '@/components/test/Test'
import Login from '@/views/login/Index'
import Index from '@/views/index/Index'
Vue.use(Router)
//原始代码
// export default new Router({
// routes: [
// {
// path: '/',
// name: 'Login',
// component: Login
// },
// {
// path: '/index',
// name: 'Index',
// component: Index,
// meta: {
// requireAuth: true,
// }
// },
//
//
//
// {
// path: '/helloWorld',
// name: 'HelloWorld',
// component: HelloWorld
// },
// {
// path: '/test',
// name: 'Test',
// component: Test
// }
// ]
// })
//增加拦截后的代码
const routes = [
{
path: '/',
name: 'Login',
component: Login,
},
{
path: '/index',
name: 'Index',
component: Index,
meta: {
requireAuth: true,
}
},
{
path: '/helloWorld',
name: 'HelloWorld',
component: HelloWorld,
meta: {
requireAuth: true,
}
},
{
path: '/test',
name: 'Test',
component: Test,
meta: {
requireAuth: true,
}
}
];
const VueRouter = new Router ({
routes,
});
VueRouter.beforeEach((to, from, next) => {
if (to.matched.some((r) => r.meta.requireAuth)) {
let user = JSON.parse(sessionStorage.getItem('user'));
if (user) { //判断是否已经登录
console.log('通过拦截',from);
next();
} else {
// this.$message({
// message: '请先登录!',
// type: 'warning'
// });
console.log('未通过拦截',from);
next({
path: '/',
query: {redirect: to.fullPath} //登录成功后重定向到当前页面
});
}
} else {
console.log('没有设置是否要拦截,直接拦截');
next();
}
//如果本地 存在 token 则 不允许直接跳转到 登录页面
if(to.fullPath === "/"){
if(sessionStorage.getItem('user')){
next({
path:from.fullPath
});
console.log('你已经登录,不能直接跳到登录页面',from);
}else {
console.log('你没有登录,可以直接跳到登录页面',from);
next();
}
}
});
export default VueRouter;