自学内容网 自学内容网

若依 Vue3 前端分离 3.8.8 版实现去除首页,登录后跳转至动态路由的第一个路由的页面

一、前言

        某些项目可能并不需要首页,但在若依中想要实现不显示首页,并根据不同角色登录后跳转至该角色的第一个动态路由的页面需要自己实现,若依中没有实现该功能的特定代码。

二、代码

1. src\permission.js

在 src\permission.js 中添加下面的代码,可将原有代码注释。

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        useUserStore().getInfo().then(() => {
          isRelogin.show = false
          usePermissionStore().generateRoutes().then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                router.addRoute(route) // 动态添加可访问路由表
                console.log(route,"route")
              }
            })
            console.log(to.fullPath,"to.fullPath")
            if (to.fullPath == '/index') {
              console.log(accessRoutes,"accessRoutes")
              // 当登录之后,直接通过ip地址和端口号访问时,跳转到第一个路由页面indexPage
              let pathIndex = ''
              //通过权限返回菜单去避免 如有首页权限 出现//index 情况
              if (accessRoutes[0].path == '/') {// 一级路由就是可以打开的页面
                pathIndex = accessRoutes[0].path + accessRoutes[0].children[0].path
                console.log(pathIndex,"pathIndex1")
              } else{// 一级路由下面的二级路由才是可以打开的页面
                 pathIndex = accessRoutes[0].path + '/' + accessRoutes[0].children[0].path
                 console.log(pathIndex,"pathIndex2")
              }
              next({ path: pathIndex, replace: true }) // hack方法 确保addRoutes已完成
            } else {
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            }
          })
        }).catch(err => {
          useUserStore().logOut().then(() => {
            ElMessage.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单,直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

2. src\store\modules\permission.js

在 src\store\modules\permission.js 的原有代码中添加下面的代码。

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: [],
      indexPage: ''   //修改默认首页
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      setIndexPages(routes) {
        this.indexPage = routes
      },
      generateRoutes(roles) {
        return new Promise(resolve => {
          // 向后端请求路由数据
          getRouters().then(res => {
            // 默认显示第一个路由,不可关闭,这三行代码一定不要忘记,否则把所有页面关闭后首页会突然跳出来而且无法关闭。
            if (res.data.length && res.data[0].children && res.data[0].children.length ) {
              res.data[0].children[0].meta.affix = true
            }
            const sdata = JSON.parse(JSON.stringify(res.data))
            const rdata = JSON.parse(JSON.stringify(res.data))
            const defaultData = JSON.parse(JSON.stringify(res.data))
            let firstPage = ''
            //通过权限返回菜单去避免 如有首页权限 出现//index 情况
            if (res.data[0].path == '/') {
              firstPage = res.data[0].path + res.data[0].children[0].path
            } else{
              firstPage = res.data[0].path + '/' + res.data[0].children[0].path
            }
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            const defaultRoutes = filterAsyncRouter(defaultData)
            const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            asyncRoutes.forEach(route => { router.addRoute(route) })
            // this.setRoutes(rewriteRoutes) 注释后就不显示 Tags-Views 中无法关闭的首页
            this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
            this.setDefaultRoutes(sidebarRoutes)
            this.setTopbarRoutes(defaultRoutes)
            this.setIndexPages(firstPage)
            resolve(rewriteRoutes)
          })
        })
      }
    }
  })

3. src\layout\components\Sidebar\Logo.vue

在 src\layout\components\Sidebar\Logo.vue 的原有代码中添加下面的代码。

:to="permissionStore.indexPage"
import usePermissionStore from '@/store/modules/permission'

const permissionStore = usePermissionStore()

4. src\components\Breadcrumb\index.vue

在 src\components\Breadcrumb\index.vue 中注释下面的代码,顶部的路径就不会显示首页字样。

5. src\router\index.js

在 src\router\index.js 中添加下面的代码,首页将不会在侧边栏中出现。

hidden: true,

三、效果

效果如图,首页相关的全都消失,登录后默认跳转到第一个路由,不同角色跳转到不同的页面,是动态路由。

四、参考

https://blog.csdn.net/YanBin_Best/article/details/140657213
https://ruoyi.csdn.net/66c84202a1ed2f4c853c6289.html

原文地址:https://blog.csdn.net/m0_57203243/article/details/142484425

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!