路由动态重定向

项目是基于vue-element-admin来写的。

具体的动态路由实现请参考,上一篇文章,此文章主要介绍动态重定向。

src/promission.js

import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import { getAccessToken } from '@/utils/auth'

const whiteList = ['/login'] //没有重定向的白名单

router.beforeEach(async (to, from, next) => {
    const hasToken = getAccessToken()
    if (hasToken) {  //是否存在token
        if (to.path === '/login') {   //访问路径是否为登录页面
            next({ path: 'index' })   //重定向到一个虚拟页面
        } else {
            // 获取到的静态路由 + 动态动态
            const hasGetPermissionRoutes = store.getters.permission_routes && store.getters.permission_routes.length > 0
            // 判断是否第一次登陆
            if (hasGetPermissionRoutes) {
                next()
            } else {
                try {
                    // const roles = store.state.user.role,原文档写法,但是这样的话 会导致刷新后,数据丢失
                    const roles = JSON.parse(localStorage.getItem('role'))
                    const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
                    let indexRou = [{ path: '/index', redirect: accessRoutes[0].redirect }] //配置跳转路由
                    router.addRoutes(indexRou) //配置的路由添加到addRouter
                    await router.addRoutes(accessRoutes) //异步加载动态路由
                    next({ ...to, replace: true })
                } catch (error) {
                    // 删除令牌并进入登录页面重新登录
                    await store.dispatch('user/removeAccessToken')
                    // Message.error(error || 'Has Error')
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    } else {
        // // has no token
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`)
        }
        // next() //重定向至login页面
    }
})

src/login/userlogin

登录模块

   this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((res) => {
              this.$router.push({ path: 'index' }); //重定向到虚拟页面,具体的跳转由src/promission做处理
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });

最后,当然是感谢我猪的独家技术支持啦~ ღ( ´・ᴗ・` )比心

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值