generateRoute.js 1.03 KB
/**
 * 生成动态路由
 */
import _ from 'lodash'
import routes from "../mock/routes"

// 根据后台返回的路径,生成页面的组件模版
function loadView(component) {
  return () => import(`/@/views/${component}.vue`)
}

const formatRoutesArr = []

routes.forEach(route => {
  const router = {}
  const {
    path,
    redirect,
    name,
    component,
    keepAlive,
    meta,
    children
  } = route

  router.component = loadView(component)
  if (redirect !== null) {
    router.redirect = redirect
  }
  if (keepAlive !== null) {
    router.keepAlive = keepAlive
  }
  if (children && children instanceof Array && children.length > 0) {
    router.children = formatRoutes(children)
  }
  if (name !== null) {
    router.name = name
  }
  if (meta !== null) {
    router.meta = meta
  }
  router.path = path

  formatRoutesArr.push(router)
})

export const generateRoute = (to) => {
  let router = ''
  _.each(formatRoutesArr, item => {
    if (item.path === to.path) {
      router = item
    }
  })
  return _.assign(to, router)
}