前端Vue2+js进行路由自动化配置

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

export const constantRoutes = [
  {
    path: '/',
    redirect: '/home',
    children: [{
      path: 'home',
      name: 'Home',
      component: () => import('@/views/Home/index'),
      meta: { title: '/home', icon: 'home' }
    }]
  },
  {
    path: '/NotFound',
    component: () => import('@/views/NotFound'),
    hidden: true
  },
  { path: '*', redirect: '/NotFound', hidden: true }
]

// 路由自动化注册
function getAutoRegisteredRoutes() {
  // require.context(目录,是否检索子文件,文件名正则表达式)
  const requireComponent = require.context('@/views', true, /.vue$/) // 找到views路径下的所有vue文件
  // keys返回所有匹配到的文件数组(包含路径)  返回类似“./NotFound.vue”和“./components/Button.vue”
  const allViewFilesPath = requireComponent.keys()
  // 过滤掉路径中包含 /_ 的文件路径,一般以“_”开头的文件夹或文件都是局部组件
  const filterFiles = allViewFilesPath.filter(path => {
    return !/\/_/.test(path)
  })
  const routesChildren = filterFiles.map(fileName => {
    // require.context 返回的是一个函数,requireComponent也就相当于一个函数
    // 返回的对象实际上是一个模块对象 有default属性
    const componentConfig = requireComponent(fileName)
    var componentName = fileName.replace(/^\.\//, '').replace(/\.vue$/, '')// 剥去文件名开头的 `./` 和`.vue`结尾的扩展名
    var componentNameRe = componentName.replace(/\//g, '-') // 设置name为文件夹名-indexcreateRouter1
    // 根据路径注册成组件  componentConfig.default会返回Vue会返回Vue 组件本身。
    const component = Vue.component(componentNameRe, componentConfig.default || componentConfig) 
    // 除去constant路由的重新注册
    if (componentName.indexOf('home/index') !== -1 || componentName.indexOf('login/index') !== -1 || componentName.indexOf('404') !== -1) {
      componentName = ''
      componentNameRe = ''
      return
    }
    const result = {
      path: componentName,
      name: componentNameRe,
      component,
      meta: { title: componentName }
    }
    return result
  })
  return routesChildren
}

function getRoutes() {
  return [
    // 如果是管理系统,需要引用组件就写在children里面
    // {
    //   path: '/',
    //   component: Layout,
    //   children: getAutoRegisteredRoutes()
    // },
    getAutoRegisteredRoutes(),
    ...constantRoutes
  ]
}

function createRouter() {
  return new Router({
    scrollBehavior: () => ({ y: 0 }),
    routes: getRoutes()
  })
}

const router = createRouter()

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值