一、了解vue–router和sessionstorage(自己百度)
官方地址
二、中main.js增加路由导航守卫
router.beforeEach((to, from, next) => {
//to.name是登录路由的名字
if (to.name!='Login') {
//token思路就是登录成功之后保存起来,然后下面拿来用
let token = sessionStorage.getItem("token")
//判断token是否已经保存了
if (token) {
//成功跳转
next()
} else {
Vue.prototype.$message({
type: "error",
message: "请先登录"
});
next('/')
}
} else {
//不能把所有路由都拦截拦,要留个登陆路由
next()
}
})
三、在验证账号密码成功后先保存token,然后中执行跳转界面
sessionStorage.setItem("token","token");
四、出现的问题
1、Uncaught (in promise) Error: Redirected when going from “/” to “/userMain” via a navigation guard.(别人说版本问题)
解决方法:中路由js文件中增加,类似于设置全局变量
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
五、可以用路由的meta来验证哪些路由需要验证(没实践过,说个想法)
meta: { requiresAuth: true }
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})