实现思路:

        1,需要在静态路由的基础上用vue路由上面的addRoute()方法来动态添加路由,最后生成我们需要的路由

        2,封装添加路由的方法,在刷新页面时重新生成路由

首先创建静态路由

// 静态路由 
export const basicRoutes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
  },
  // 免登录跳转到项目中
  {
    path: '/hideLogin',
    name: 'hideLogin',
    component: () => import('@/views/hideLogin/index.vue'),
  },
  {
    // 异常页面
    path: '/errorPage',
    component: () => import('@/components/error-page/404'),
    name: '404',
  },
]

创建路由的时候引入

import { createRouter, createWebHistory } from 'vue-router'
import { basicRoutes as routes } from './routes' // 引入静态路由

export const router = createRouter({
  history: createWebHistory('/'),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})
export default router

封装处理路由方法

import { deepClone } from '@/utils/utils' // 深拷贝
import router from './index'
// 处理路由展示列表树形格式 (如果所有路由数据是在同一级,需要调用这个方法)
export const formatRouterTree = (data) => {
  let parents = data.filter((i) => i.pid === 0),
    children = data.filter((item) => item.pid !== 0)
  dataToTree(parents, children)
  function dataToTree(parents, children) {
    parents.map((p) => {
      children.map((c, i) => {
        let _c = deepClone(children)
        _c.splice(i, 1)
        dataToTree([c], _c)
        if (p.children) {
          p.children.push(c)
        } else {
          p.children = [c]
        }
      })
    })
  }
}

// vite中获取文件
const modules = import.meta.glob([
  '../views/*.vue',
  '../views/*/*.vue',
  '../views/*/*/*.vue',
  '../components/layout/index.vue',
])

// 处理路由所需格式
export const generateRouter = (userRouters) => {
  let newRouter = null
  if (userRouters)
    newRouter = userRouters.map((i) => {
      let routes = {
        path: i.pathUrl,
        name: i.name,
        // meta: i.meta,
        component:
          i.pathUrl === '/layout'
            ? modules[`../components/layout/index.vue`]
            : modules[`../views${i.pathUrl}/index.vue`],
      }
      if (i.children) {
        routes.children = generateRouter(i.children)
      }
      return routes
    })
  return newRouter
}

/**
 * 添加动态路由
 */
export function setAddRoute(routes) {
  if (routes && routes.length > 0)
    routes.forEach((route) => {
      const routeName = route.name
      if (!router.hasRoute(routeName)) router.addRoute(route)
    })
}

在store中写一个调用方法

import { defineStore } from 'pinia'
import { generateRouter, setAddRoute } from '@/router/vue-router.js'
export const routeStore = defineStore('route', {
  state: () => {
    return {
    }
  },
  actions: {
    addRouter() {
      // 生成路由树
      // routerList在登陆成功时获取到,在跳转页面之前存起来
      let find = JSON.parse(window.localStorage.getItem('routerList'))
      let routerList = generateRouter(find)
      // 添加路由
      setAddRoute(routerList)
    },
  },
  getters: {},
})

登陆时存储路由信息

import { generateRouter, setAddRoute } from '@/router/vue-router.js'

Login.Login(params).then(async (res) => {
     if (res.code === 200) {
        // 存用户信息、token等,这里不写了

        // 调接口获取路由信息 params传当前用户角色来获取对应的路由信息
        let routerList = await getRouterList(params)
        // 存储路由信息
        window.localStorage.setItem('routerList', routerList)
        
        // 生成路由树
        let list = generateRouter(routerList)
        // 添加路由
        setAddRoute(list)
        
        // 最后跳转到首页并提示
        router.push('首页')
        ElMessage.success('登陆成功')
     }  
})

解决刷新消失

上面只是在登陆时候添加了路由,点击刷新页面后会消失,需要在main.js中配置一下

import { createPinia } from 'pinia'
import { routeStore } from '@/store/modules/routeMenu.js' // 这个是我的store里面的方法路径
const store = createPinia()
const app = createApp(App)
app.use(store)
let routeStores = routeStore()
const addRouter = () => {
  routeStores.addRouter()
}
addRouter()
// router要在添加完路由之后引入,不然还没添加,路由已经生成了
app.use(router)

Logo

前往低代码交流专区

更多推荐