ts的动态路由

把component转为函数,组件路径要写对

export function convertRouter(asyncRoutes: any) {
  asyncRoutes = asyncRoutes.filter((item: any, index: Number) => index === 0)
  return asyncRoutes.map((route: any) => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = (resolve: any) => require(['@/layout/index.vue'], resolve)
      } else if (route.component === 'LayoutC') {
        route.component = (resolve: any) => require(['@/layout/index.vue'], resolve)
      } else {
        if (typeof (route.component) === 'string') {
          const index = route.component.indexOf('views')
          const path =
            index > 0 ? route.component.slice(index) : `${route.component}`
          route.component = (resolve: any) => require([`@/${path}`], resolve)
        }
      }
    }
    if (route.children === undefined) route.children = []
    if (route.children && route.children.length) { route.children = convertRouter(route.children) }
    if (route.children && route.children.length === 0) delete route.children
    console.log(route, 'sadasdsa')
    return route
  })
}

路由守卫的时候再处理检验路由及添加路由,不要重复

防止页面刷新,vuex数据(路由)丢失

router.beforeEach(async (to: Route, _: Route, next: any) => {
  // Start progress bar
  NProgress.start()
  // Determine whether the user has logged in
  if (UserModule.token) {
    if (to.path === '/login') {
      // If is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      console.log('router to page')
      if (PermissionModule.dynamicRoutes.length === 0) {
        await UserModule.AddAsyncRoute()
        next({ ...to, replace: true })
      } else next()
      //     Message.error(err || 'Has Error')
      //     next(`/login?redirect=${to.path}`)
      //     NProgress.done()
    }
  } 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}`)
      NProgress.done()
    }
  }
  NProgress.done()
})

router相关的数据类型

Route,路由对象,获取路由
RouteConfig[]:初始化路由

router的一些api

GenerateRoutes:get Routes,save in vuex(SET_ROUTES)
addRoute设置路由
PermissionModule.dynamicRoutes.forEach(route => {
router.addRoute(route)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值