vue 动态路由无法显示组件

白大魔王
  • 55

如题,通过登录再获取menu数据,动态配置路由和左侧菜单。

router.js部分代码如下:

import login from '@/components/login'
import home from '@/components/business/home'
import store from '../components/store/index'
import { getAsyncRoutes } from './asyncRouter'

Vue.use(Router)
// 没有涉及权限的公共路由
export const constantRoutes = [
  {
    path: '/home',
    name: 'home',
    component: home
  },
  {
    path: '/login',
    name: 'login',
    component: login
  }
]

const createRouter = ()=> new Router({
  mode: 'history',
  scrollBehavior: ()=> ({ y: 0 }),
  routes: constantRoutes
})
const router = createRouter()

const whiteList = ['/login']
router.beforeEach(async (to, from, next)=> {
  // 获取用户token,用来判断当前用户是否登录
  const hasToken = localStorage.getItem('token')
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/login' })
    } else {
      // 异步获取store中的路由
      let route = await store.state.mutations.roters
      const hasRouters = route && route.length > 0
      // 判断store中是否有路由,若有,进行下一步
      if (hasRouters) {
        next()
      } else {
        // store中没有路由,则需要获取获取异步路由,并进行格式化处理
       try {
          const accessRoutes = getAsyncRoutes(await store.state.mutations.roters)
          // 动态添加格式化过的路由
          router.options.routes = accessRoutes
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
          console.log(router)
        } catch (error) {
          // Message.error('出错了')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

getAsyncRoutes方法为遍历数据并创建对应的component:

getAsyncRoutes(routes) {
    routes.forEach(item=> {
    const newItem = {}
    if (item.path) {
      newItem.component = ()=> import('../components/business/user')
       // newItem.component = resolve=> require(['../components/business/user.vue'], resolve)
      newItem.name = item.path
      newItem.path = item.path
      res.push(newItem)
    }
    // 存在子路由,需对子路由进行递归遍历
    if (newItem.children && newItem.children.length) {
      getAsyncRoutes(item.children)
    } 
  })
  return res
}

但这样加载的路由始终无法跳转页面,打印路由出来,正常的路由home和user对比:
image.png
home是可以正常跳转显示的,其他的都无法展示,import和require都试过,
望大神一解困扰,感激不尽!

回复
阅读 896
2 个回答
✓ 已被采纳

使用
require(路径).default
import是异步的,你addRoutes的时候根本还没获取到页面数据的。

newItem.component = (resolve)=> require(['../components/business/user'],resolve)

你知道吗?

宣传栏