问题
在做vue项目中,有这样的场景,直接打开某个web页面,我们都会做登录状态的判断,已登录的话,会跳转当前页,未登录会跳转至登录页,登录成功后再跳转。
今天我们来说说登录成功后怎样跳转到登录之前的页面。
实现
钩子介绍
在路由跳转的时候,我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数。
定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。
总体来讲vue里面提供了三大类钩子,两种函数
全局钩子
某个路由的钩子
组件内钩子
两种函数:
Vue.beforeEach(function(to,form,next){}) /在跳转之前执行/
Vue.afterEach(function(to,form)) /在跳转之后判断/
beforeEach函数三个参数:
to : router即将进入的路由对象
from : 当前导航即将离开的路由
next : Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
afterEach函数不用传next()函数
这里我们通过全局钩子实现
代码实现
步骤一
其中当要跳转到登录页的时候我们加了参数:redirect,参数值即为该页面路径,用作登录成功后的跳转
next({
path: "/login",
query: {
redirect: to.fullPath
} //将目的路由地址存入login的query中
})
整体代码
router.beforeEach((to, from, next) => {
if (store.getters.token) { // 判断是否有token
// console.log(store.getters.name)
if (to.path === '/login') {
next({
path: '/'
})
} else {
if (store.getters.roles == undefined || store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
store.dispatch('GetInfo').then(res => { // 拉取user_info
const roles = res.data.role
store.dispatch('GenerateRoutes', {
roles
}).then(() => { // 生成可访问的路由表
router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
next({
...to
}) // hack方法 确保addRoutes已完成
console.log(store.getters.addRouters)
})
}).catch(() => {
store.dispatch('FedLogOut').then(() => {
next({
path: '/login',
query: {
redirect: to.fullPath
}
})
})
})
} else {
store.dispatch('getNowRoutes', to);
// if (hasPermission(localStorage.getItem('auth'), to.meta.role)) {
if (hasPermission(localStorage.getItem('auth'), to)) {
// if (hasPermission(store.getters.roles, to.meta.role)) {
next() //
console.log("has userinfo")
} else {
next({
path: '/',
query: {
noGoBack: true
}
})
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入(无需要登录的页面)
next()
} else {
next({
path: "/login",
query: {
redirect: to.fullPath
} //将目的路由地址存入login的query中
})
}
}})
步骤二
当登录成功后,在登录方法中,通过this.$route 去拿到redirect参数值,该参数值就是要跳转的路径,直接跳转即可
if (this.$route.query.redirect == undefined) {
this.$router.push({ path: '/' });
} else {
this.$router.push({ path: this.$route.query.redirect })
}