vue路由自动配置(require.context)

require.context函数接受三个参数

directory {String} -读取文件的路径

useSubdirectories {Boolean} -是否遍历文件的子目录

regExp {RegExp} -匹配文件的正则

语法: require.context(directory, useSubdirectories = false, regExp = /^.//)

/*
 * @Description: 获取文件名自动配置路由
 * @Author: Benny
 * @Date: 2019-08-02 16:20:18
 * @LastEditTime: 2019-09-26 14:41:48
 */
import Vue from 'vue';
import Router from 'vue-router';

let routesConfig = [] //路由配置
const files = require.context('./views', true, /\.vue$/)

files.keys().forEach(key => {

  let path = key.replace(/(\.\/|\/index|\.vue)/g, ''), //将./ /index  .vue 置换为空白
    fileUrl = key.replace(/\.\//g, './views/'),//匹配路径
    len = path.split('/').length,
    name = files(key).default.name || path.split('/')[len - 1] //获取文件夹名

  if (fileUrl.indexOf('index.vue') != -1 && fileUrl.indexOf('signup') == -1) {  //判断是否包含 index且排除singup入口文件
    routesConfig.push({
      path: `/${path}`,
      name: name,
      meta: {
        title: name
      },
      component: () => import(`${fileUrl}`)
    })
  }


})

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    ...routesConfig
  ],
  scrollBehavior(to,from,savedPosition){
    return {
      x:0,
      y:0
    }
  }
})

router.beforeEach((to, from, next) => {//beforeEach是router的钩子函数,在进入路由前执行
  if (to.meta.title) {//判断是否有标题
    document.title = to.meta.title
  }
  next()//执行进入路由,如果不写就不会进入目标页
})

export default router;



还有个问题..
路由嵌套暂时解决不了= =
望有知道的大佬指点~
目前暂时是有需求的嵌套独立成一个路由变量然后合并到routes里头

//教师注册转换连路由
const signupRouter = [
  {
    path: '/signup',
    redirect: '/signup/resume', //重定向
    name: 'signup',
    component: () => import('views/signup/home'),
    children: [
      {
        path: 'resume',
        meta: { title: '填写简历' },
        component: () => import('views/signup/resume')
      },
      {
        path: 'train',
        meta: { title: '入职培训' },
        component: () => import('views/signup/train'),
        children:[
          {
            path: 'book',
            meta: { title: '预约培训' },
            component: () => import('views/signup/train/block/_Book')
          },
          {
            path: 'detail',
            meta: { title: '待上课' },
            component: () => import('views/signup/train/block/_BookDetail')
          },
          {
            path: 'exam',
            meta: { title: '测试' },
            component: () => import('views/signup/train/block/_Exam')
          },
          {
            path: 'result',
            meta: { title: '测试结果' },
            component: () => import('views/signup/train/block/_Result')
          },
          {
            path: 'upload',
            meta: { title: '上传教学照片' },
            component: () => import('views/signup/train/block/_Upload')
          },
          {
            path: 'video',
            meta: { title: '观看录像' },
            component: () => import('views/signup/train/block/_Video')
          }
        ]
      }
    ]
  },
]

你可能感兴趣的:(vue路由自动配置(require.context))