Vue Router 前置导航守卫:实现用户角色权限控制
// 前置导航守卫\nrouter.beforeEach((to, from, next) => {\n const token = localStorage.getItem('token');\n const rolesLocal = localStorage.getItem('roles');\n const requiresAuth = to.meta.requiresAuth;\n const roles = to.meta.roles;\n\n // 如果该路由有权限且未登录,则跳转登录页面\n if (requiresAuth && !token) {\n alert("请先登录!");\n next("/login");\n } else {\n // 需要鉴权且登录\n if (token && roles && rolesLocal) {\n if (rolesLocal === "admin") {\n // 判断用户角色,用户角色正确则放行,否则阻止跳转\n if (roles.includes(rolesLocal)) {\n alert("欢迎您管理员!");\n next('/home');\n } else {\n alert("权限不够!");\n next(false);\n } \n } else if (rolesLocal === "teacher" || rolesLocal === "admin") {\n // 判断用户角色,用户角色正确则放行,否则返回上一页面\n if (roles.includes(rolesLocal)) {\n alert("欢迎您优秀的教师!");\n next('/teacherhome');\n } else {\n alert("权限不够!");\n next(false);\n } \n } else if (rolesLocal === "user" || rolesLocal === "admin") {\n // 判断用户角色,用户角色正确则放行,否则返回上一页面\n if (roles.includes(rolesLocal)) {\n alert("精英教育欢迎您的到来!");\n next('/userhome');\n } else {\n alert("权限不够!");\n next(false);\n } \n } else if (to.name === "notfound" || to.name === "login") { // 添加判断条件,如果当前路由是登录页面,则放行\n next();\n } else {\n next("/error");\n } \n } else {\n // 不需要鉴权且未登录\n if (!requiresAuth && !token) {\n next();\n } else {\n console.log("error");\n next();\n } \n } \n } \n})\n\n// 使用afterEach导航守卫\nrouter.afterEach((to, from) => {\n const rolesLocal = localStorage.getItem("roles");\n\n console.log(Navigated from ${from.fullPath} to ${to.fullPath})\n console.log(to.meta.roles);\n console.log(to.meta.roles.includes(rolesLocal));\n})\n// 代码报错原因分析:\n// 这段代码出现错误的原因可能是因为在使用导航守卫时,需要先创建一个Vue Router实例,然后将其应用到Vue实例中。可以尝试按照以下步骤进行修改:\n// 1. 首先,确保已经安装了Vue Router并导入Vue和Vue Router库。\n// 2. 创建一个Vue Router实例,并将路由配置项传递给它。\n// javascript\n\/\/ import Vue from 'vue';\n\/\/ import VueRouter from 'vue-router';\n\/\/ \n\/\/ Vue.use(VueRouter);\n\/\/ \n\/\/ const router = new VueRouter({\n\/\/ routes: [\n\/\/ \/\/ 路由配置项\n\/\/ ]\n\/\/ });\n\/\/ \n// 3. 在创建Vue实例之前,将Vue Router实例应用到Vue实例中。\n// javascript\n\/\/ new Vue({\n\/\/ router, \/\/ 将Vue Router实例引入Vue实例\n\/\/ render: h => h(App),\n\/\/ }).$mount('#app');\n\/\/ \n// 通过以上步骤进行修改后,再次运行代码,应该就不会报错了。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pQyr 著作权归作者所有。请勿转载和采集!