使用beforeEach实现权限设置,和上节用Vue-Router 的 beforeEach属性 实现路由导航守卫用法基本一样,知识需要在路由routers添加一个meta属性,对用户类型进行判断就可以了
直接上代码:
const router = new Router({
routes: [{
path: "/",
name: "login",
component: login
},
{
path: "/Teacher",
name: "Teacher",
meta: {
admin: true,
teacher: true,
student: false
},
component() {
return import(/* webpackChunkName: "Teacher" */ "./views/Teacher/index.vue");
},
children: [
// 这里写教师端的子页面
{
path: "/Teacher/userlist",
name: "userList",
meta: {
admin: true,
teacher: true,
student: false
},
component() {
return import(/* webpackChunkName: "userList" */
"./views/Teacher/user_manage/index.vue"
);
}
}
}
}
router.beforeEach((to, from, next) => {
const cookieData = getCookie("SignInstate"); // cookie赋值给变量, 判断登录否
if (to.name === "login") {
if (cookieData === "true") {
// 普通判断是否登录
const TOKEN = JSON.parse(localStorage.dcaw_token);
if (TOKEN.role === "admin" || TOKEN.role === "teacher") {
next({
path: "/Teacher/experimentManage"
});
} else if (TOKEN.role === "student") {
next({
path: "/Student/practice"
});
}
} else {
next();
}
} else if (cookieData === "false") {
// if (to.name ==='forgetpassword') {
// next()
// } else {
next({
path: "/"
});
// }
} else {
const TOKEN = JSON.parse(localStorage.dcaw_token);
if (to.meta[TOKEN.role]) { // to 所指向的meta属性的对应的登录用户类型
next();
} else {
// eslint-disable-next-line no-alert
alert("暂无访问权限");
return;
}
}
if (localStorage.getItem("checked") === "true") {
const TOKEN = JSON.parse(localStorage.dcaw_token);
if (to.name === "login") {
if (TOKEN.role === "admin" || TOKEN.role === "teacher") {
next({
path: "/Teacher/experimentManage"
});
} else if (TOKEN.role === "student") {
next({
path: "/Student/practice"
});
}
}
}
});